What is Gradle in Flutter and How to Use It?
Hello everyone, I am Mirze Muhammed Ko?ak, and I will explain the relationship between Gradle and Flutter, an essential tool in both Flutter and Android development.
What is Gradle?
Gradle is an open-source, flexible, and performant build automation tool designed for large and complex software development projects. It supports multiple programming languages such as Kotlin, Java, C++, and more, and is commonly used for project management and compilation. At least one Gradle build file is located in the root directory of a project. It supports many programming languages but is most commonly used with Java and Kotlin.
When we create a project in Flutter and want to compile it for Android, the Gradle build system comes into play.
Some features of Gradle are as follows:
Where is Gradle used?
?
What are the basic concepts of Gradle?
Gradle covers a large portion of the features of other build automation tools and is better in many aspects. For detailed information, it is necessary to examine and compare other build automation tools.
Why use Gradle?
Gradle is written in Java. Gradle is configured using a Java and Groovy-based Domain-Specific Language (DSL), but Gradle itself is developed in the Java language and runs on the Java Virtual Machine (JVM).
Gradle's main components and operations are written in Java, but Groovy or Kotlin DSL is used for Gradle configurations. This makes Gradle a highly flexible and customizable build tool.
When was Gradle first used in Flutter?
In the early stages, the build system used in Flutter and Dart was called Bazel. However, as Flutter rapidly grew and became tightly integrated with Android, it transitioned to the more widely-used Gradle system, which plays a significant role in Android development.
Bazel:
Gradle:
So, while Bazel was used in the early stages of Flutter development, Gradle became prominent during the period when Flutter was officially and widely adopted.
What is the Android project structure in Flutter?
The Android project structure is as follows, but since the focus of this article is Gradle, we will only examine the Gradle structure. Therefore, we will only keep the Gradle-related parts of the project structure open, and our new view looks like this:
Now, let's learn step by step what each part does.
android/build.gradle (Root-level build.gradle)
What it does: It is the main configuration file of the project. It contains the general configurations of the Flutter application (e.g., Gradle version, dependencies, and configuration options). This file includes the buildscript and allprojects blocks and is written in the Groovy language.
buildscript: Contains configurations for Gradle and its plugins, for example, the version of the Android Gradle plugin is specified here.
allprojects: Defines common settings and dependencies for all subprojects. This section is part of the "root-level" Gradle configuration file and defines general configurations that affect the entire project (both root and subprojects).
Code Explanations:
allprojects { repositories { ... } }
What it does: Defines dependency repositories common to all projects (both root and subprojects).
google(): Uses Google's Maven repository, which contains the libraries and tools needed for Android applications.
mavenCentral(): A central Maven repository that hosts libraries commonly used in Java and Android projects.
rootProject.buildDir = "../build"
What it does: Specifies where the build files of the root project (main project) will be placed. By default, the build folder is located in the project directory; here, the build folder is moved to the parent directory (../build).
subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" }
What it does: Defines where the build files for subprojects (e.g., the :app module) will be placed. Each subproject is placed in the root project's build directory (../build/{sub_project_name}), under a folder named after the subproject.
subprojects { project.evaluationDependsOn(":app") }
What it does: Specifies that the subprojects depend on the evaluation of the :app project. This means that the :app module must be evaluated before the subprojects are evaluated. This is often used to avoid issues related to dependencies or build sequencing.
tasks.register("clean", Delete) { delete rootProject.buildDir }
What it does: Defines a task named clean in Gradle. This task deletes all files and folders under rootProject.buildDir (i.e., the ../build folder).
tasks.register: A Gradle-specific command used to register a new task.
Delete: A class in Gradle used to delete specified files or directories.
delete: Specifies the files or directories to be deleted. Here, it deletes the rootProject.buildDir, i.e., the build directory of the root project.
These codes are used to apply the Gradle configuration across the entire project and define common configurations among the projects. They define where dependencies are pulled from, organize where build files are stored, set the project evaluation order, and create a clean task to clean the build outputs.
android/app/build.gradle (Module-level build.gradle)
What it does : Contains the module-level configurations of the application. It includes settings such as the app's version, package name, minimum and target SDK versions, dependencies, and build options. In the dependencies block, libraries required by the app are defined. The code on this page is written in Groovy and belongs to the Gradle configuration file used to compile Android apps. The build.gradle file contains the necessary configurations for building and running your Android app. Below, I will explain the purpose of each section of the code.
This code is written in Groovy and is part of the Gradle configuration used to build Android applications.
Code explanations:
1. plugins { ... }?
?? - Purpose: Defines the necessary plugins for the project. In this case:
???? - id 'com.android.application': Allows the application to be built as an Android app.
???? - id 'kotlin-android': Plugin required to support the Kotlin language.
???? - id 'dev.flutter.flutter-gradle-plugin': A specific Gradle plugin for Flutter, necessary for configuring and building a Flutter app.
?2. android { ... }?
?? - Purpose: Defines the general configuration and features of the Android app.
?? - namespace: Specifies the app's namespace, similar to a Java or Kotlin package name, identifying the app uniquely.
?? - compileSdk: Defines the Android SDK version the app will be compiled against, indicating up to which Android version the app is supported.
?? - ndkVersion: Specifies the version of the Native Development Kit (NDK), often used for compiling native code written in C/C++.
?3. compileOptions { ... }?
?? - Purpose: Defines the Java compiler options for the project.
?? - sourceCompatibility and targetCompatibility: Specifies which version of Java the project is compatible with. VERSION_1_8 corresponds to Java 8.
?4. kotlinOptions { ... }?
?? - Purpose: Specifies the JVM target for Kotlin.
?? - jvmTarget: Defines which version of the JVM the Kotlin code will target, with VERSION_1_8 corresponding to Java 8 compatibility.
?5. defaultConfig { ... }?
?? - Purpose: Contains the app’s default configurations.
?? - applicationId: The unique identifier for the app, which must be different for every Android application.
?? - minSdk: Specifies the minimum Android SDK version that the app will support.
?? - targetSdk: Specifies the target Android SDK version for the app.
?? - versionCode: The version code of the app, which must be incremented with every new release.
?? - versionName: The user-friendly version number of the app (e.g., "1.0.0").
?6. buildTypes { ... }?
?? - Purpose: Defines the build types of the app.
?? - release: Contains the configurations for the release build. Here, the signingConfig is set to the debug configuration, meaning the app is signed for testing purposes.
?7. flutter { ... }?
?? - Purpose: Specifies the configuration options related to Flutter.
?? - source: Indicates the source directory for Flutter code.
?This code is used to define how the Android app will be built, which versions it will support, and various configurations of the application.
android/gradle/ Directory
What it does: Contains the files necessary for the Gradle wrapper. The Gradle wrapper is used to build the project with a specific version of Gradle. This directory contains the wrapper subdirectory and the gradle-wrapper.properties file:
??gradle-wrapper.properties: The configuration file for the Gradle wrapper. It specifies which version of Gradle to use and the Gradle distribution URL.
领英推荐
This configuration code refers to the Gradle Wrapper settings used in Flutter projects. The Gradle Wrapper ensures that builds are carried out reliably. Below, I will explain what each setting means in the context of Flutter:
1. distributionBase=GRADLE_USER_HOME:
?? Specifies the base directory where the downloaded Gradle version will be stored. GRADLE_USER_HOME is a user-specific Gradle folder. This defines where the distribution files used by the Gradle Wrapper will be saved.
?2. distributionPath=wrapper/dists:
?? Specifies the path where the downloaded Gradle version will be stored. For Flutter projects, this path defines the subdirectory where the downloaded Gradle version will be saved.
?3. zipStoreBase=GRADLE_USER_HOME:
?? Defines the base directory where the Gradle distributions downloaded by the Gradle Wrapper will be stored. In Flutter projects, this setting defines the main directory for storing the downloaded Gradle version.
?4. zipStorePath=wrapper/dists:
?? Specifies the path where the ZIP files downloaded by the Gradle Wrapper will be stored. In Flutter, these files contain the Gradle components necessary to build the project.
?5. distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip:
?? Specifies the URL of the Gradle version that will be used by the Gradle Wrapper. For Flutter projects, this URL defines which version of Gradle will be downloaded and used to run Android build tasks. In this case, the gradle-8.3-all.zip file will be downloaded and used.
android/settings.gradle
What it does: Informs Gradle which modules (subprojects) are included in this project. In Flutter projects, this file typically only defines the ':app' module.
?This code is found in the settings.gradle file. The settings.gradle file plays a crucial role in managing the project’s modules and configurations.
Code explanation:
?1. pluginManagement { ... }:
?? The pluginManagement block is used to configure Gradle plugin management. Within this block, code that defines the location of the Flutter SDK and installs required dependencies is present.
?2. def flutterSdkPath = { ... }():
?? Defines the flutterSdkPath variable and uses a Java Closure to retrieve the Flutter SDK path. Let’s look at the details:
?? - def properties = new Properties(): Creates a new Properties object to read the Flutter SDK path from the local.properties file.
?? - file("local.properties").withInputStream { properties.load(it) }: Opens the local.properties file in the project directory and loads its content into the properties object. This file contains the Flutter SDK path.
?? - def flutterSdkPath = properties.getProperty("flutter.sdk"): Retrieves the value of the flutter.sdk key from the local.properties file, specifying the path to the Flutter SDK.
?? - assert flutterSdkPath != null, "flutter.sdk not set in local.properties": If the flutter.sdk value is null (not defined), the build is stopped with an error message, ensuring the Flutter SDK path is properly defined.
?? - return flutterSdkPath: Returns the Flutter SDK path.
?3. includeBuild("$flutterSdkPath/packages/flutter_tools/gradle"):
?? This line includes the Flutter tools (flutter_tools) necessary for the Gradle build within the Flutter SDK. It ensures that Flutter’s tools (such as the plugin loader) are correctly used in the project.
?4. repositories { ... }:
?? Defines which repositories should be used to fetch dependencies.
?? - google(): Uses Google’s Maven repository, which is required for Android SDK and Google dependencies.
?? - mavenCentral(): Uses the Maven Central repository, which hosts a large number of Java and Kotlin libraries.
?? - gradlePluginPortal(): Specifies the Gradle Plugin Portal as a source for Gradle plugins.
?5. plugins { ... }:
?? Defines which Gradle plugins to use:
?? - id "dev.flutter.flutter-plugin-loader" version "1.0.0": Adds the plugin loader required for Flutter projects.
?? - id "com.android.application" version "8.1.0" apply false: Specifies the Gradle plugin used for building Android apps. The apply false means it will not be applied directly here but can be used elsewhere.
?? - id "org.jetbrains.kotlin.android" version "1.8.22" apply false: Specifies the Gradle plugin used for Kotlin-based Android development. Similarly, the apply false indicates it will not be applied here.
?6. include ":app":
Indicates that the ':app' module is included in the project. This refers to the main Android application module.
android/gradle.properties
What it does: A Gradle configuration file that contains runtime settings and memory configurations for Gradle. For example, it can define memory allocation settings for the JVM and parallel build options.
Code explanations:
?1. org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError:
Purpose: Specifies configuration options for the Java Virtual Machine (JVM) during Gradle builds.
Xmx4G: Sets the maximum heap memory that the JVM can use to 4 GB. This is used to speed up the build process for large projects and to prevent "Out of Memory" errors.
XX:MaxMetaspaceSize=2G: Limits the Metaspace (the memory area where the JVM stores class metadata) to 2 GB. This helps prevent memory-related errors when loading classes.
?XX:+HeapDumpOnOutOfMemoryError: Instructs the JVM to create a heap dump when an "Out of Memory" error occurs. This dump can be useful for diagnosing memory leaks.
?2. android.useAndroidX=true:
Purpose: Tells Gradle that the project is using AndroidX, a newer version of Android support libraries. In Flutter projects, this setting ensures compatibility with modern Android libraries.
?3. android.enableJetifier=true:
Purpose: Enables Jetifier, a tool that converts old Android support libraries to their AndroidX equivalents. This is necessary when using libraries that haven’t fully migrated to AndroidX yet.
android/local.properties
What it does: Specifies the path to the Android SDK. Flutter or Android Studio locates the SDK using the path defined in this file. It typically contains settings specific to the local development environment and is not included in source control.
Code Explanation:
?1. sdk.dir=C:\\Users\\muhammed\\AppData\\Local\\Android\\Sdk:?
?? This line specifies the local directory where the Android SDK is installed. In this path:
?? - sdk.dir: A key that defines the location of the Android SDK.
?? - C:\\Users\\muhammed\\AppData\\Local\\Android\\Sdk: The absolute path where the Android SDK is installed. (In Windows environments, directory paths are specified using double backslashes \\).
?2. flutter.sdk=C:\\Users\\muhammed\\dev\\flutter:
?? This line specifies the local directory where the Flutter SDK is installed. In this path:
?? - flutter.sdk: A key that defines the location of the Flutter SDK.
?? - C:\\Users\\muhammed\\dev\\flutter: The absolute path where the Flutter SDK is installed.
?Function of the Code:
These paths are necessary for Flutter and Android tools to work on a project. Below is a detailed explanation of the function of each setting:
?1. sdk.dir:?
?? This setting specifies where Android Studio or Gradle can find the Android SDK. The Android SDK contains all the tools and libraries needed to develop, build, and test Android applications. In a Flutter project, the SDK is required to build the Android side of the app.
?2. flutter.sdk:?
?? This setting defines the location of the Flutter SDK. The Flutter SDK contains the tools, command-line utilities, and libraries necessary for developing mobile applications (iOS and Android) with Flutter. The project uses this directory when accessing Flutter commands (such as flutter build, flutter run, etc.).
Importance for a Flutter Project:
Path Definition: These settings automatically provide the SDK paths to project configuration files (e.g., settings.gradle, build.gradle), ensuring that Flutter and Android components can be found and used properly.
Environment Compatibility: Ensures that different developers or machines use the same SDK versions when building the project, preventing configuration mismatches.
Local Development Convenience: The local.properties file contains configurations specific to the local environment, so this file is typically not tracked by version control. This allows each developer to set up the appropriate paths on their own machine.
Conclusion:
These settings define the necessary paths for the Flutter and Android SDKs to function correctly in the local development environment. This ensures that the required tools and libraries are accessible when building or running the project.
android/.gradle/ Directory
What it does: Contains cache and intermediate files generated by Gradle. It is typically created and stored when the project is built.
gradlew and gradlew.bat
What it does: These are Gradle wrapper scripts. gradlew is used for Unix-based operating systems (Linux, macOS), while gradlew.bat is used for Windows. These scripts ensure that the project is built with a specific version of Gradle. Even if Gradle is not installed on the user's system, the project can be built using these files.
Thank you for reading, don't forget to follow me
#flutter #gradle #android
source
Bayburt üniversitesi e?itim kurumunda ??renci
6 个月Mirze Muhammet KO?AK tebrikler ??