Hrishikesh Pathak

The complete guide to building, testing, and deploying flutter apps with codemagic CI/CD

The complete guide to building, testing, and deploying flutter apps with codemagic CI/CD

Flutter is a cross-platform UI framework developed by Google. Initially, flutter was started as a UI framework for android and iOS. But with time, flutter is expanded to cover all the major desktop operating systems and web browsers.

Now I think the obvious question that comes to your mind is, don’t we have a native framework and language for each platform. For example, android has java and Kotlin, iOS have swift and c#. The apps made with those techs are very performant and run smoothly on their respective platform. They also follow some platform-specific design guidelines. This helps users quickly learn to use a new app.

But with flutter, we don’t have any design restrictions, the app performance is not as per the native apps. So why do we bother to use flutter? Yes, this is a genuine question one can ask before learning flutter.

My take on this is flutter provides a good developer experience. Yes, it is not as performant as the native one, but we are heading this way. Also, the primary reason to use flutter is its platform independence. You just have to write once and deploy anywhere it supports.

In 2022, if you are looking for a truly cross-platform framework for your product or startups, then flutter would be the right choice for you.

After writing and building the flutter application, app deployment and distribution is a cumbersome process for a developer. Whether it is a team or a solo project, we developers love to code. We want to make a product. We don’t want to deal with deployment and distribution.

There are many moving parts involved in app deployment. Whether it is google play store or apple App Store, one human error can lose all your hard work. To solve this issue, modern software developers use continuous integration and delivery (CI/CD) to automate this app testing and deployment process.

Codemagic is such a service that you can use to integrate a (CI/CD) pipeline into your workflow. If abstract out all your complexities and give you a much smoother development and deployment experience. Click here to register for free and start deploying with codemagic.

Agenda of the article

In this article, we are going to build a flutter app from scratch. Then write some tests to test the core logic of the app. After that, we hook the codemagic CI/CD pipeline to make a release build of our app. Finally, we set up continuous deployment of our app to the google play store with the help of codemagic.

The brief point-wise agenda of this article is as follows :

  • Create a flutter app
  • Pull some data from a remote API and display it inside our app
  • Test the core logic with unit test and mocking the API request
  • Build our app for deployment with codemagic
  • Automate deployment with codemagic to the google play store

Build a flutter app

Before starting, let’s create a new flutter project. Use the --org tag for defining the package name of your app. The package name of your app is a unique identifier for your app. This will help you to push the update to your app and distinguish and support the legitimacy of your application.

Defining the package name at the start makes our life a lot easier during deployment. Otherwise, you have to go files after files to change your package name before building of your app.

For package names, you should use a unique domain name. If your domain name is, then you have to put com.example as your package name.

1# Change com.example to your unique domain name
2flutter create --org com.example codemagicdemo

Fetch data from API

Now your project is up and running. You can verify this by simply running flutter run command inside your terminal. This command will launch a debug version of your app inside any device of your choice.

Our primary task in this guide is to fetch some data from a remote API. Then we process the API response and display it inside our app. The API response contains a list of authors, along with their author details, their names, description and a Wikipedia link, etc.

If you paste this link into your browser, you will see what the API response looks like.

To consume this data inside out app, we have to decode the response with jsonDecode() and hook it with some dart classes for ease of use.

At first, we make an AuthorList class. It wraps all the json fields we need from the API response.

Create a file called author_list.dart. Here we define the aforementioned class. The fields inside AuthorList look like this.

1class AuthorList {
2 final int count;
3 final int totalCount;
4 final int page;
5 final int totalPage;
6 final List<Author> results;
8 const AuthorList({
9 required this.count,
10 required this.totalCount,
11 required,
12 required this.totalPage,
13 required this.results,
14 });

As you can see, in the results field, we use a list of a custom type called Author. This class wrap all the json response field we need for an individual author.

To define the Author class, create a file called author.dart. The fields inside the Author class look something like this.

1class Author {
2 final String id;
3 final String name;
4 final String slug;
5 final String bio;
6 final String description;
7 final int quoteCount;
8 final String link;
9 final String dateAdded;
10 final String dateModified;
12 const Author({
13 required,
14 required,
15 required this.slug,
16 required,
17 required this.description,
18 required this.quoteCount,
19 required,
20 required this.dateAdded,
21 required this.dateModified,
22 });

We are done with making all the dart wrappers for the API response. Now Let’s fetch the data from the API.

Create a file called network_service.dart. All our networking logic goes inside this file. In this example, I use the standard http package to make the network request.

To install this package, at the root of your project, run this command.

1flutter pub add http

Then create a NetworkService class. Inside this NetworkService class we define fetchAuthorList() method. This method will be responsible for calling and decoding all the API requests.

After we get the response from the server, if the response status code is 200, we decode this response with jsonDecode() function. Then we hook the json data into our previously made AuthorList and Author class (or object).

At this point, the code inside the NetworkService looks something like this.

1import 'dart:convert';
2import 'package:codemagicdemo/src/data/author.dart';
3import 'package:http/http.dart' as http;
4import './author_list.dart';
6class NetworkService {
8 final String baseurl = "";
10 Future<AuthorList> fetchAuthorList() async {
11 http.Response response = await http.get(
12 Uri.parse("$baseurl/authors"),
13 );
15 if (response.statusCode == 200) {
16 Map<String, dynamic> decodedResult =
17 jsonDecode(response.body);
19 return AuthorList(
20 count: decodedResult["count"],
21 totalCount: decodedResult["totalCount"],
22 page: decodedResult["page"],
23 totalPage: decodedResult["totalPages"],
24 results: (decodedResult["results"] as List)
25 .map(
26 (e) => Author(
27 id: e["_id"],
28 name: e["name"],
29 slug: e["slug"],
30 bio: e["bio"],
31 description: e["description"],
32 quoteCount: e["quoteCount"],
33 link: e["link"],
34 dateAdded: e["dateAdded"],
35 dateModified: e["dateModified"],
36 ),
37 )
38 .toList(),
39 );
40 } else {
41 throw Exception("Failed to load Author list");
42 }
43 }

Building the UI

For now, the network service section is over. Let’s focus on building a beautiful UI for our app.

UI is the part with which our user interacts. So making it good and polished makes the user experience better.

We make 2 screens. The first one is the home screen. Here we display all the authors as a list inside a ListView. When the user clicks on any of the list items, a second screen will open.

The second screen consists of details of individual authors with their Images.

The final app will look like this.


Let’s build the home screen first. Make a scaffold inside a stateful widget. Inside the body of the scaffold, we define a FutureBuilder. This FutureBuilder listen for the API response. When the Network_service finished processing the API response, it renders the AuthorList as a ListView on the Homescreen.

The complete code of the homepage looks like this.

1import 'package:flutter/material.dart';
2import '../data/network_service.dart';
3import '../data/author_list.dart';
4import '../widgets/custom_listile.dart';
6class Homepage extends StatefulWidget {
7 const Homepage({Key? key}) : super(key: key);
10 State<Homepage> createState() => _HomepageState();
13class _HomepageState extends State<Homepage> {
15 late Future<AuthorList> authorList;
18 void initState() {
19 authorList = NetworkService().fetchAuthorList();
20 super.initState();
21 }
24 Widget build(BuildContext context) {
25 return Scaffold(
26 appBar: AppBar(
27 title: const Text("Authors"),
28 ),
29 body: FutureBuilder<AuthorList>(
30 future: authorList,
31 builder: (context, snapShot) {
32 if (snapShot.hasData) {
33 return ListView.builder(
34 itemCount:,
35 itemBuilder: ((context, index) => CustomListTile(
36 author:!.results[index],
37 )),
38 );
39 }
40 return Center(
41 child: CircularProgressIndicator(
42 color: Theme.of(context).primaryColor,
43 ),
44 );
45 },
46 ),
47 );
48 }

On the homepage, every author is displayed as a list element inside a CustomListTile. This CustomListTile is just a regular ListTile with a bit of customization on top of it. when we click on the CustomListTile, it takes us to the second screen. we name the second screen as author_detail_page.dart.

The code inside the CustomListTile is as follows.

1import 'package:flutter/material.dart';
2import '../data/author.dart';
3import '../pages/author_detail_page.dart';
5class CustomListTile extends StatelessWidget {
6 final Author author;
7 const CustomListTile({Key? key, required}) : super(key:
8 key);
11 Widget build(BuildContext context) {
12 return Container(
13 margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
14 child: ListTile(
15 contentPadding: const EdgeInsets.symmetric(vertical: 7,
16 horizontal: 15),
17 shape: RoundedRectangleBorder(
18 side: const BorderSide(
19 color: Color(0xFFEFEFEF),
20 width: 1,
21 style: BorderStyle.solid,
22 ),
23 borderRadius: BorderRadius.circular(5),
24 ),
25 enableFeedback: true,
26 tileColor: Theme.of(context).backgroundColor,
27 leading: CircleAvatar(
28 backgroundColor: Theme.of(context).primaryColor,
29 child: Icon(
30 Icons.account_circle_outlined,
31 color: Theme.of(context).primaryIconTheme.color,
32 ),
33 ),
34 trailing: Icon(
35 Icons.arrow_forward_rounded,
36 color: Theme.of(context).primaryIconTheme.color,
37 ),
38 title: Text(,
39 onTap: () {
40 Navigator.push(
41 context,
42 MaterialPageRoute(
43 builder: (_) => AuthorDetailsPage(
44 author: author,
45 ),
46 ),
47 );
48 },
49 ),
50 );
51 }

Inside the author_detail_page.dart we need to render the image of the individual author. We can get the author image from an API with the help of a slug associated with Author object. The URL for the image will look like this:{slug}.jpg.

The process is simple. Just manipulate the image URL with the individual author slug and add the URL inside a network image widget. flutter will do the rest for us.

Get the author’s image

Now let’s go back to our network_service.dart file. Inside the NetworkService class, add another method called authorImageLink(). This method takes the slug of an individual author and gives us the required image link.

After all that set up, our final network_service.dart file looks something like this.

1import 'dart:convert';
2import 'package:codemagicdemo/src/data/author.dart';
3import 'package:http/http.dart' as http;
4import './author_list.dart';
6class NetworkService {
8 final String baseurl = "";
9 final String imageBaseUrl =
10 "";
12 String authorImageLink({required String slug}) {
13 return "$imageBaseUrl$slug.jpg";
14 }
16 Future<AuthorList> fetchAuthorList() async {
17 http.Response response = await http.get(
18 Uri.parse("$baseurl/authors"),
19 );
21 if (response.statusCode == 200) {
22 Map<String, dynamic> decodedResult =
23 jsonDecode(response.body);
25 return AuthorList(
26 count: decodedResult["count"],
27 totalCount: decodedResult["totalCount"],
28 page: decodedResult["page"],
29 totalPage: decodedResult["totalPages"],
30 results: (decodedResult["results"] as List)
31 .map(
32 (e) => Author(
33 id: e["_id"],
34 name: e["name"],
35 slug: e["slug"],
36 bio: e["bio"],
37 description: e["description"],
38 quoteCount: e["quoteCount"],
39 link: e["link"],
40 dateAdded: e["dateAdded"],
41 dateModified: e["dateModified"],
42 ),
43 )
44 .toList(),
45 );
46 } else {
47 throw Exception("Failed to load Author list");
48 }
49 }

Then inside the author_detail_page we call this authorImageLink() method inside a NetworkImage with the required slug and then the image is displayed on the screen. As a grain of salt, I add the image loading progress percentage with the loadingBuilder argument in NetworkImage. This gives a nice look to our app.

Last but not least, remember we have a Wikipedia link for each author. Now I use a package called url_launcher to launch the Wikipedia link from the app.

To add this package to your app, run the following command.

1flutter pub add url_launcher

Till now both of our screens are completed. The code snippets of the second screen is:

1import 'package:flutter/material.dart';
2import 'package:url_launcher/url_launcher.dart';
3import '../data/author.dart';
4import '../data/network_service.dart';
6class AuthorDetailsPage extends StatefulWidget {
7 final Author author;
9 const AuthorDetailsPage({Key? key, required}) : super(key:
10 key);
13 State<AuthorDetailsPage> createState() => _AuthorDetailsPageState();
16class _AuthorDetailsPageState extends State<AuthorDetailsPage> {
19 Widget build(BuildContext context) {
20 return Scaffold(
21 appBar: AppBar(
22 title: const Text("Details"),
23 ),
24 body: Container(
25 width: double.maxFinite,
26 margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
27 decoration: BoxDecoration(
28 color: Theme.of(context).backgroundColor,
29 borderRadius: BorderRadius.circular(5),
30 ),
31 child: Column(
32 mainAxisAlignment: MainAxisAlignment.start,
33 crossAxisAlignment:,
34 mainAxisSize: MainAxisSize.min,
35 children: [
36 const SizedBox(height: 20),
38 NetworkService().authorImageLink(slug:,
39 frameBuilder: ((context, child, frame, wasSynchronouslyLoaded)
40 { return Container(
41 height: 100,
42 width: 100,
43 decoration: BoxDecoration(
44 shape:,
45 border: Border.all(
46 color: Theme.of(context).primaryColor, width: 4),
47 ),
48 child: ClipOval(
49 child: child,
50 ),
51 );
52 }),
53 loadingBuilder: (context, child, loadingProgress) {
54 if (loadingProgress != null) {
55 double loadingpercent =
56 loadingProgress.cumulativeBytesLoaded /
57 loadingProgress.expectedTotalBytes!.toInt();
58 if (loadingpercent < 1) {
59 return Container(
60 decoration: BoxDecoration(
61 shape:,
62 border: Border.all(
63 color: Theme.of(context).primaryColor, width: 4),
64 ),
65 height: 100,
66 width: 100,
67 child: Center(
68 child: Text("${(loadingpercent *
69 100).toStringAsFixed(2)} %",
70 style:
71 Theme.of(context).primaryTextTheme.displayMedium,
72 ),
73 ),
74 );
75 }
76 }
77 return child;
78 },
79 ),
80 const SizedBox(height: 20),
81 Text(,
82 style: Theme.of(context).primaryTextTheme.titleMedium,),
83 const SizedBox(height: 5),
84 Text(,
85 style: Theme.of(context).primaryTextTheme.titleSmall,
86 ),
87 const SizedBox(height: 20),
88 Padding(
89 padding: const EdgeInsets.symmetric(horizontal: 20),
90 child: Text(,
91 style: Theme.of(context).textTheme.bodyMedium,
92 textAlign:,
93 ),
94 ),
95 const SizedBox(height: 40),
96 TextButton(
97 onPressed: () {
98 launchUrl(
99 Uri.parse(,
100 );
101 },
102 child: const Text("Know more"),
103 ),
104 const SizedBox(height: 10),
105 ],
106 ),
107 ),
108 );
109 }

The project structure of the app inside the lib/ folder looks something like this. You can also see the Github repository for this project here.

2├── generated_plugin_registrant.dart
3├── main.dart
4└── src
5 ├── app.dart
6 ├── data
7 │ ├── author.dart
8 │ ├── author_list.dart
9 │ └── network_service.dart
10 ├── pages
11 │ ├── author_detail_page.dart
12 │ └── homepage.dart
13 └── widgets
14 └── custom_listile.dart

Write some tests

In this article, we are only going to write unit tests. Unit tests are very small tests inside our app to check the core logic of our app. The is the simplest one and very easy to maintain.

As we are working with live data, and remote data is very unpredictable, we will use a mocking library to mock the API response. This will help to make our unit test faster and also help us to reduce unintended test fails.

For mocking, we use mocktail package. A lot of guides and even flutter official documentation recommend using the mockito package for mocking data. But this involves a code generation step which I don’t like.

I use mocktail and like it (a bit biased). You can use whatever you want. It is as per your choice.

If you are very new to flutter and don’t know how to write tests in a flutter, follow this official guide.

Test Network service

To test the network service, make a new file network_service_test.dart inside the test/ directory at the project root. Inside the file, let’s mock the NetworkService class. for that write

1import 'package:mocktail/mocktail.dart';
3class MockNetworkService extends Mock implements NetworkService {}

Inside the main function, we define the mockservice variable. Then we write a setup function. This function runs before every test. Inside the setup function, we initialize the mock network service.

1void main(){
2 late MockNetworkService mockservice;
4 setUp(() {
5 mockservice = MockNetworkService();
6 });

At first, we test if we can invoke the fetch_author function. For that, the test would look like

1test("Test if fetch author function is invoked", () {
2 when(() => mockservice.fetchAuthorList())
3 .thenAnswer((_) async => authorList);
5 verifyNever(() => mockservice.fetchAuthorList());
6 mockservice.fetchAuthorList();
7 verify(() => mockservice.fetchAuthorList()).called(1);
8 });

when, verify, verifyNever functions are coming from the mocktail package. Click here to know more.

Then we will test the if fetchAuthor function returns an author list. For that, first we have to define an author list as a mock. the list will look like this.

1AuthorList authorList = const AuthorList(
2 count: 20,
3 totalCount: 700,
4 page: 1,
5 totalPage: 35,
6 results: [
7 Author(
8 id: "yBDYq_Vtnuw",
9 name: "A. A. Milne",
10 slug: "a-a-milne",
11 bio: "Alan Alexander Milne (18 January 1882 31 January 1956) was an
12 English author, best known for his",
13 description: "British author",
14 quoteCount: 2,
15 link: "",
16 dateAdded: "2019-08-08",
17 dateModified: "2019-08-08")
18 ],

Then our test code snippets will be,

1test("Test to see if fetch author list returns", () async {
2 when(() => mockservice.fetchAuthorList())
3 .thenAnswer((_) async => authorList);
4 AuthorList actualAuthorList = await mockservice.fetchAuthorList();
5 expect(actualAuthorList, authorList);

At last, we will test if our authorImageLink method returns a usable link to render in the network image widget.

1test("If author image link is reachable", () {
2 when(() => mockservice.authorImageLink(slug: "a-a-milne"))
3 .thenReturn("
4 milne.jpg");
5 expect(mockservice.authorImageLink(slug: "a-a-milne"),
6 "");
7 }

Till now all our 3 unit tests completed. As all of the tests are related to the NetworkService class, we can group them inside a single group. The complete code inside network_service_test.dart will be,

1import 'package:codemagicdemo/src/data/author.dart';
2import 'package:codemagicdemo/src/data/author_list.dart';
3import 'package:codemagicdemo/src/data/network_service.dart';
4import 'package:flutter_test/flutter_test.dart';
5import 'package:mocktail/mocktail.dart';
7class MockNetworkService extends Mock implements NetworkService {}
9void main() {
10 AuthorList authorList = const AuthorList(
11 count: 20,
12 totalCount: 700,
13 page: 1,
14 totalPage: 35,
15 results: [
16 Author(
17 id: "yBDYq_Vtnuw",
18 name: "A. A. Milne",
19 slug: "a-a-milne",
20 bio:
21 "Alan Alexander Milne (18 January 1882 31 January 1956) was an English author, best known for his",
22 description: "British author",
23 quoteCount: 2,
24 link: "",
25 dateAdded: "2019-08-08",
26 dateModified: "2019-08-08")
27 ],
28 );
30 late MockNetworkService mockservice;
32 setUp(() {
33 mockservice = MockNetworkService();
34 });
36 group("test http call to the network", () {
37 test("Test if fetch author function is invoked", () {
38 when(() => mockservice.fetchAuthorList())
39 .thenAnswer((_) async => authorList);
40 verifyNever(() => mockservice.fetchAuthorList());
41 mockservice.fetchAuthorList();
42 verify(() => mockservice.fetchAuthorList()).called(1);
43 });
44 });
46 test("Test to see if fetch author list returns", () async {
47 when(() => mockservice.fetchAuthorList())
48 .thenAnswer((_) async => authorList);
49 AuthorList actualAuthorList = await mockservice.fetchAuthorList();
50 expect(actualAuthorList, authorList);
51 });
53 test("If author image link is reachable", () {
54 when(() => mockservice.authorImageLink(slug: "a-a-milne"))
55 .thenReturn("");
57 expect(mockservice.authorImageLink(slug: "a-a-milne"),
58 "");
59 });

Always try to write an elaborate description of tests. This will help you to debug your code faster and become very easy to understand, what is going on inside the tests.

To run the test, you can use the small run button displayed at the top of the test function inside VSCode. Or if you are a terminal guy like me, you can run the following command.

1flutter test test/network_service_test.dart

Deploy with codemagic

Till now all our app building and testing phases are done. It feels relaxing right. Now one last task is due and then we are all done after that. Congratulations !!

If you want, take a break, and have some coffee. If you like, you can also buy me a coffee. You are appreciated 😉.

Push to Github (or Gitlab, Bitbucket etc)

Once you are done writing your app, commit all of your changes. Navigate to your project root and run

1git add .git commit -m"Your commit message"

Then create a new repository on GitHub. Copy the http link of the repository. Then run

1git branch -M maingit remote add origin <http link of your repo>git push -u origin main

After running these commands, refresh your newly created Github repository to see your project files.

Make a release build with codemagic

To make a release build of our app, just follow the official flutter guide till the reviewing Gradle build configuration.

Then log in to the codemagic dashboard. If you don’t have an account, make one with GitHub sign-in. This makes your life easier and pulls your flutter project from the GitHub repo easily.


If you are a new user, codemagic will show you a getting started screen. You can choose your flutter project repository. Then select the Flutter project (with workflow editor) option. Then a new workflow editor will open.


This is the place where you can customize all the settings to build your app.

Customize the build in codemagic

In the build trigger tab, click on the trigger on push. Now whenever you push to your main branch, a new build will take place.

In the watch branch pattern, you can choose your required branch. It can be main or your branch of choice.


Inside the Tests tab, click on the Enable flutter test option.


Inside the Build tab, select Flutter version as Master. Choose release option inside mode parameter.


Inside the distribution tab, under android code signing, click on enable android code signing and upload the Keystore file. This Keystore file is generated while you are following the flutter build and release documentation in the previous step.

Now you have to add a Keystore password, key password, and an alias. Remember you have given all this information while creating the Keystore.


Now you are done. It is easy right. Just click on the start new build. Codemagic will pull the code from your GitHub repo and build the app on your behalf on their machine.

When the app will finish building, you can download the artifacts to test on your device.

I have covered only some surface-level details in this article. For more information, visit this official documentation.

Deploy to play store using codemagic CI/CD

Now, this is the last and the most interesting part of this article. Imagine you push your code to GitHub and a new version of your app will be built and deployed on the play store automatically. This seems magic, right? This is why it is called codemagic 😁.

Once you set up all these build and deployment workflows, All of the tedious tasks of building and releasing your app will be handled by codemagic.

To set up your play store for CI/CD, and create a new application in your google play console. Then upload an internal testing release to it. This is very important to do, otherwise, codemagic gives you error after error. I have learned this the hard way and I don’t want to go through the same pain.

Then follow these codemagic guides to set up all the required configurations. This is very elaborate and well-written documentation. Don’t skip anything. Just follow step by step.

After all the step is done, you will get a .json key from google cloud. Store it in a safe place. we need it later.

Then you can decorate your app store with a beautiful app icon, cover image, and some screenshots of the app.

If you published an app in the play store before, remember they (the play store guys) review every app before release. Until your app is not reviewed and accepted, you can only upload a draft release inside your google play console.


Now come back to the codemagic editor, and inside the distribution tab, you can see an option called google play. Click to enable google play to publish. Upload the JSON key you received from the above step.

Choose the track option carefully. As you are app is not reviewed yet. You can’t make a release. So for the time being, I choose the internal track. Then don’t forget to click on submit as a draft.

After your app is reviewed by them, you can choose any release track as per your choice and you can untick the submit as draft as an option.


After all these steps, this is the time to hit the Start new build button. Are you excited? me too.

If all things go well, you can see something like this. Now your app will be submitted as a draft inside your play console.


Congratulation. You have done it. If you are following this far, then I have to say, you have a passion to learn. I feel glad that I can produce such long content that people read. If you have any problems and want to discuss something, ping me on Twitter.

Codemagic is such a useful tool if you are a small group or solo dev. It saves a lot of time for you. Do try it out and write your experiences. I will love to hear from you. Till then, bye and happy coding.