Simplifying Flutter Deployment with FastLane
Tags: flutter, fastlane, android, cicd
Published: 2024-02-04 09:44:27

# **Introduction**

In the world of mobile app development, efficiency and automation are key. FastLane offers a suite of tools designed to automate the deployment of mobile apps, making it an indispensable tool for Flutter developers. This guide will walk you through setting up FastLane for Android and macOS, ensuring a smoother deployment process for your Flutter apps.

## **Getting Started with FastLane**

### Install FastLane

1. Android
- install Ruby
    - you can use **[RubyInstaller](https://rubyinstaller.org/) or  the following terminal commands**
    - make sure to open the terminal as an administrator  (Windows users only)
    
    ```powershell
    choco install ruby # you must have Chocolatey package manager 
    gem install bundler
    ruby --version
    ```
    
- Install Fastlane
    
    ```powershell
    gem install fastlane
    ```
    
- set environment variables
    - open: environment variables form search bar
    - under system variables add those keys and values
        

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ylzjg0rp0w8771a6gk7i.png)
        
        LC_ALL ⇒ en_US.UTF-8
        LANG ⇒ en_US.UTF-8
        FLUTTER_ROOT=<Your flutter root file>
        
1. macOS
- install ruby
    - open terminal the write
    
    ```bash
    brew install ruby && sudo gem install bundler && ruby --version 
    ```
    
- Install Fastlane
    
    Homebrew needs to be installed before executing **`brew`** commands, as new macOS users might not have it installed. 
    
    ```bash
    brew install fastlane
    ```
    
- set environment variables
    - open: finder then go to the top bar click Go ⇒ home
    - after opening home click cmd&shift&. to see the hidden files then open .zprofile file
    - add those lines to your .zprofile file
        
        ```bash
        export PATH="/opt/homebrew/opt/ruby/bin:$PATH”
        export LC_ALL=en_US.UTF-8
        export LANG=en_US.UTF-8
        export FLUTTER_ROOT="<Your flutter root file>" # examle /Users/alimaher/fvm/default/
        ```
        

# FastLane For Android

- **Setting up *fastlane***
    - In the Visual Studio Code terminal, navigate to the Android folder `cd android`
    - then run `fastlane init`

You'll be asked to confirm that you're ready to begin, and then for a few pieces of information. To get started quickly:

1. Provide the package name for your application when asked (e.g. io.fabric.yourapp)
2. Press enter when asked for the path to your json secret file
3. Answer 'n' when asked if you plan on uploading info to Google Play via fastlane (we can set this up later)

That's it! *fastlane* will automatically generate a configuration for you based on the information provided.

You can see the newly created `./fastlane` directory, with the following files:

- `Appfile` which defines configuration information that is global to your app
- `Fastfile` which defines the "lanes" that drive the behavior of *fastlane*
- **Setting up *supply***

*supply* is a *fastlane* tool that uploads app metadata, screenshots and binaries to Google Play. You can also select tracks for builds and promote builds to production!

For *supply* to be able to initialize, you need to have successfully uploaded an APK to your app in the Google Play Console at least once.

Setting it up requires downloading a credentials file from your Google Developers Service Account.

### **Collect your Google credentials**

**Tip:** If you see Google Play Console or Google Developer Console in your local language, add `&hl=en` at the end of the URL (before any `#...`) to switch to English. All the links below already have this to make it easier to find the correct buttons.

**Note:** if you face issues when following these instructions, you might want to refer to the [official documentation by Google](https://developers.google.com/android-publisher/getting_started/?hl=en).

1. Open the [Google Play Console](https://play.google.com/console/?hl=en)
    1. Click **Account Details**, and note the **Developer Account ID** listed there
1. Enable the [Google Play Developer API](https://console.developers.google.com/apis/api/androidpublisher.googleapis.com/?hl=en) by selecting an existing Google Cloud Project that fits your needs and pushing **ENABLE**
    1. If you don't have an existing project or prefer to have a dedicated one for *fastlane*, [create a new one here](https://console.cloud.google.com/projectcreate/?hl=en) and follow the instructions
2. Open [Service Accounts on Google Cloud](https://console.cloud.google.com/iam-admin/serviceaccounts?hl=en) and select the project you'd like to use
    1. Click the **CREATE SERVICE ACCOUNT** button at the top of the **Google Cloud Platform Console** page
    2. Verify that you are on the correct Google Cloud Platform Project by looking for the **Developer Account ID** from earlier within the light gray text in the second input, preceding `.iam.gserviceaccount.com`, or by checking the project name in the navigaton bar. If not, open the picker in the top navigation bar, and find the right one.
    3. Provide a `Service account name` (e.g. fastlane-supply)
    4. Copy the generated email address that is noted below the `Service account-ID` field for later use
    5. Click **DONE** (don't click **CREATE AND CONTINUE** as the optional steps such as granting access are not needed):
        
        
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k906w8qug3dhpqeyzrdb.png)


        
    6. Click on the **Actions** vertical three-dot icon of the service account you just created
    7. Select **Manage keys** on the menu
    8. Click **ADD KEY** → **Create New Key**
    9. Make sure **JSON** is selected as the `Key type`, and click **CREATE**
    10. Save the file on your computer when prompted and remember where it was saved at
3. Open the [Google Play Console](https://play.google.com/console/?hl=en) and select **Users and Permissions**
    1. Click **Invite new users**
    2. Paste the email address you saved for later use into the email address field
    3. Click on **Account Permissions**
    4. Choose the permissions you'd like this account to have. We recommend **Admin (all permissions)**, but you may want to manually select all checkboxes and leave out some of the **Releases** permissions such as **Release to production, exclude devices, and use Play App Signing**
    5. Click on **Invite User**

You can use
 `[fastlane run validate_play_store_json_key json_key:/path/to/your/downloaded/file.json](https://docs.fastlane.tools/actions/validate_play_store_json_key/)` to test the connection to Google Play Store with the downloaded private key. Once that works, add the path to the JSON file to your [Appfile](https://docs.fastlane.tools/advanced/Appfile):

```ruby
json_key_file("path/to/your/play-store-credentials.json")
package_name("my.package.name")
```

### **Fetch your app metadata**

If your app has been created on the Google Play developer console, you're ready to start using *supply* to manage it! Run:

```
fastlane supply init

```

and all of your current Google Play store metadata will be downloaded to `fastlane/metadata/android`.

## Test and deploy

- internal test
    - open: `android/fastlane/Fastfile` file, in this file you will add your setting for upload new aab for internal testing.
    
    ```ruby
    default_platform(:android)
    
    # upload to internal test to Google Play
    lane :internal do 
      # build the app bundle if you haven't already 
      gradle(task: 'bundleRelease')
      # Upload to internal test
      upload_to_play_store(
        track: 'internal',
        aab: '../build/app/outputs/bundle/release/app-release.aab', # Update this path if your AAB is generated in a different location
        skip_upload_apk: true,
        skip_upload_images: true,
        skip_upload_screenshots: true,
        skip_upload_metadata: true,
        skip_upload_changelogs: true,
        skip_upload_aab: false,
      )
    end
    
    ```
    
    - now increase your build number in pubspec.yaml
    - now in your terminal run the following commands:
    
    ```bash
    flutter clean
    flutter pub get
    flutter build appbundle
    cd ./android/
    fastlane internal # Now you will push your aab to the internal test
    cd ..
    ```
    
    ---
    
- release
    - open: `android/fastlane/Fastfile` file, in this file you will add your sitting for upload new aab for internal testing.
    
    ```ruby
    default_platform(:android)
    
    # upload release to Google Play
    lane :release do
      gradle(task: 'bundleRelease')
      # Upload to internal test
      upload_to_play_store(
        track: 'production',
        aab: '../build/app/outputs/bundle/release/app-release.aab', # Update this path if your AAB is generated in a different location
        skip_upload_apk: true,
        skip_upload_images: true,
        skip_upload_screenshots: true,
        skip_upload_metadata: true,
        skip_upload_changelogs: true,
        skip_upload_aab: false,
      )
    end
    ```
    
    - now increase your build number in pubspec.yaml
    - now in your terminal run the following commands:
    
    ```bash
    flutter clean
    flutter pub get
    flutter build appbundle
    cd ./android/
    fastlane release # Now you will push your aab to the internal test
    cd ..
    ```
    
    ---
    
- increase version number automatically
- add script.rb file:
    
    create new file `script.rb` in android folder: `andoird/script.rb`
    
    this code will edit in your pubspec.yaml file to increase your version
    
    ```ruby
    # pubspec_path = '../pubspec.yaml'
    pubspec_path = File.expand_path('../../pubspec.yaml', __FILE__)
    
    # Read the file into an array of lines
    lines = File.readlines(pubspec_path)
    
    # Find the line containing the version and update it
    lines.map! do |line|
      if line.strip.start_with?('version:')
        if line =~ /(\d+)\.(\d+)\.(\d+)\+(\d+)/
          major, minor, patch, build = $1.to_i, $2.to_i, $3.to_i, $4.to_i
          patch += 1
          build += 1
          line = "version: #{major}.#{minor}.#{patch}+#{build}\n"
        end
      end
      line
    end
    
    # Write the updated lines back to the file
    File.open(pubspec_path, 'w') { |file| file.puts(lines) }
    ```
    

- open: `android/fastlane/Fastfile` file, in this file you will add your sitting for increase your version number automatically

```ruby
lane :icrease_build_number do
  # script.rb is a ruby script that increments the build number in pubspec.yaml
  system("ruby ../script.rb")
end
```

- now increase your build number in pubspec.yaml
- now in your terminal run the following commands:

```bash
cd ./android/
fastlane icrease_build_number 
cd ..
```

- you can use both of release or internal and icrease_build_number fastlane action to fully automate your deployment steps using this code:

```bash
cd ./android/
fastlane icrease_build_number
cd ..
flutter clean
flutter pub get
flutter build appbundle
cd ./android/
fastlane release # or use internal 
cd ..
```