Google search engine
Home Blog Page 36

How Flutter Renders Widgets?

0

In this Article, We are going to learn about How Exactly Flutter Renders Widgets. This may might not be a Key-Facets in the Daily development of Flutter Apps but will surely give you up a Prominent Understanding about making of Performant Flutter Apps & what constitutes behind the idea of Flutter Working under the Hood.

For Novice,

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase.

To get a visual understanding through the help of video , Please watch:

“Everything is a widget in Flutter”

So, In order to understand Widget rendering in flutter . Let’s see what the flutter document has to say about Widget in its official documentation .

But what might will come up in your mind is that how can User Interface be Immutable (unchangeable) as we all know that UIs are not at all immutable as we readily mutate different parts of our UIs by swapping pieces in|out by adding divergent widgets. So, If Widgets are Immutable then

How Does Flutter Manage State of your UI?

Apparently, what Flutter does is that It actually manages this through with the help of 3 trees instead of a Singleton for the State Management.

Amalgamating these 3 different concepts, Make the rendering of a UI as performant as as we possibly can.

Flutter manage these 3 Different tree in for its rendering process:

So we’ve already seen that a widget is immutable,and so that kind of makes sense because you are working with a declarative framework so you grasp what your UI is going to like like & configure it with widgets.

Widget describe configuration of an element which are particularly an instantiation of those widget. It can also be termed as the mutable piece of the tree or It’s the thing that manages updating and changing of the UI , controlling lifecycle of widgets .

Thirdly, we have a RenderObject which is what’s going to lay out and paint your UI.

What needs to be Amply Clear here is that on the point of widget drawing , Flutter does not look at the Widget tree but the RenderObject tree.

But Why are we even creating 3 trees ?

For this we need to drop down onto the level & look at source code from flutter framework for when it create a flutter app.

Step-by-Step Walkthrough ::

Flutter app calls runApp() function initially:

It takes the Widget given by the runApp and put it at root of tree.

Widget then creates the LeafRenderObjectElement called leaf, as tree are only one level deep with one widget. Element then request creation of RenderObject and passes all of the configuration needed to paint the widget. Now we have our widget trees but what if we wanna do some changes:

Let’s run it again and see what happens

You want to change some aspect of your widget so what happens when something changes in our widget.You probably will still be asking Why are we doing this amount of task to get one thing on screen ,this will unfold when:

Magic really happens when things change

This can be understood by setting 2 runApp function:

Flutter realises it has done the stipulated amount of needed work so how it can reuse it. It will then call canUpdate method which can be performed when either : runtime or keys of widgets match. Alas, Render Paragraph is updated — Element update next time it paints UI. Using our RenderObject tree its going to paint new values:

We have readily swapped one immutable widget though we have neither created|destroyed anything much- used a simple update method here , Optimising amount of work needed going from one UI state to other — Ensuring that we Reuse .

Reuse: This can be easily shown by a Demo which readily shows that if the render object element is same flutter reuse most if its components so that it can maintain the desired frame-per-second.

Demo::

The above flutter app has 2 trees which are almost identical with a row consisting- RichText , SizedBox & Image .

What’s the dire need as we know is that on widget rebuilding no new RenderObject should be created — RenderObject should remain Same .

This can be Illustrated with the help of Dart Dev Tools that can be considered as browser based tools to debugging and analysing flutter Apps.For Overview about Dart Devtools::

:: Opening Dart DevTools , Widget tree will be shown on one side and other side shows instance id of RenderObject:

We can readily see that on switching the tree — instance id of all(RichText SizedBox & Image) have remained the same . This is illustrated in DartDevTools by tapping on SwitchTree that even though widget tree is changed — new text and image are displayed but their RenderObject are bound to remain Same but No change is not all we need as in flutter things change Readily. To consider change I have removed the Sizedboxwith a completely different widget , Padding

When flutter realises it has now a different widget , Padding so that it does need SizedBox now .It completely destroys it and create a completely different RenderObject for padding but that’s Intended to happen . What needs to be kept in mind is that instance id of all other widget have remained the same .

Closing Thoughts

Flutter application usually possess multiple widgets with several layers of depth across a broad spectrum making it exorbitant in rebuilding widgets making it the optimum reason why flutter has adopted this method of using three concepts to minimise amount of processing it needs to do to make these changes. Let’s refresh reponsibility of these 3 tree:-

::Widget : Configure User Interface.

::Element :Ensure when things change updates are done accordingly.

::Render object : Sizes & Paint UIs on Screen.

So Yeah this is the reason Why Flutter and Dart enthusiasts are Elated with the Performance they are getting from Flutter Apps and been Quite Eventful in Paving Up Paths for many to Adapt early to this Wondrous Framework. Hopefully, this blog will help you in comprehending out the Widget Rendering in flutter by adding a Perfect Competitive niche to your knowledge base .


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

We welcome feedback, and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸

Moor in Flutter(Tables and Queries)

0

Moor is just a Room spelled backward. Moor is a library allowing us to work with Flutter’s SQLite database fluently and in pure Dart. Moor also uses SQLite package. In flutter, it becomes very easy to create a database without writing code for SQL tables. Moor itself uses SQL as its backend so in flutter we can directly create a Table using Dart


Table of content

  1. Why Moor?
  2. Adding the dependency
  3. Creating a Table
  4. The Database class
  5. Queries
  6. User Interface

Why Moor?

  • Moor enables us to write queries in dart and SQL.
  • Provide us APIs in dart as well.
  • Moor provides Tables, queries, migration, IDE for SQL, complex filters.
  • Moor helps you keep your database code simple and easy to understand.
  • Identify or catches the error and provides the solution
  • Moor is fast like FLUTTER.
  • Moor works on Android, iOS, macOS, Windows, Linux, and the web.
  • Moor is stable and well tested with a wide range of unit and integration tests. It powers the production of Flutter apps.

Adding the dependency

  1. moor_flutter:

This is the core package that provides APIs.

2. moor_generator:

Generate query code based on the Table defined by the user.

3. build_runner:

Tool for database code generation.

4. pubspec.yaml

dependencies:
moor_flutter:
dev_dependencies:
moor_generator:
build_runner:

Creating a Table

A Table in dart is made by just extending our dart class to Table. Moor uses this Table and database class to create a Database.

  1. SQL Table in dart
import 'package:moor_flutter/moor_flutter.dart';
part 'moor_database.g.dart';

class Orders extends Table {
TextColumn get price => text()();
IntColumn get id => integer().autoIncrement()();
TextColumn get productName => text()();

}
@UseMoor(tables: [Orders])
class AppDatabase{
}

Here IntColumn, TextColumn are the Table datatypes that are used to define the type of data that will the column of Table carries.

part 'moor_database.g.dart';

This is the file name that will contain the code generated using the Table. The id for each item in a column is id since it is autoIncrement().

2. Custom key

We can also provide our custom id to the table by just overriding the primaryKey.

@override
Set<Column> get primaryKey => {id, productName};

The Database class

@UseMoor(tables: [Orders])
class AppDatabase extends _$AppDatabase {
AppDatabase()
: super(FlutterQueryExecutor.inDatabaseFolder(
path: "db.sqlite", logStatements: true));
int get schemaVersion => 1;
}

After creating this Database class we need to generate the moor_Database.g.dart file. So we have to run the below command in the terminal.

flutter packages pub run build_runner build

Here we are defining the path inside the Database folder and we are setting the logStatements to true. It will help in debugging.


Queries

These queries are given inside the AppDatabase class.

  1. Queries in pure Dart with moor
Future<List<Order>> getAllOrder() => select(orders).get();
Stream<List<Order>> watchAllOrder() => select(orders).watch();
Future insertNewOrder(Order order) => into(orders).insert(order);
Future deleteOrder(Order order) => delete(orders).delete(order);

select()

You can create select statements by starting them with select(tableName), where the table name is a field generated for you by the moor. Each table used in a database will have a matching field to run queries against. Any query can be run once with get() or be turned into an auto-updating stream using watch().

Future<List<Order>> getAllOrder() => select(orders).get();
Stream<List<Order>> watchAllTask() => select(orders).watch();

insert() & delete()

We can also insert any object into the Table.

insert and delete statement take a Tables, in this case, we have Order as our Table.

Future insertNewOrder(Order order) => into(orders).insert(order);
Future deleteOrder(Order order) => delete(orders).delete(order);

update()

This statement also uses the Table to update the targeted attribute using the constructor of the Table.

Future updateOrder(Order order) => update(orders).relpace(order);

2. Full Code for moor_database.dart file

import 'package:moor_flutter/moor_flutter.dart';
part 'moor_database.g.dart';

class Orders extends Table {
TextColumn get price => text()();
IntColumn get id => integer().autoIncrement()();
TextColumn get productName => text()();

}

@UseMoor(tables: [Orders])
class AppDatabase extends _$AppDatabase {
AppDatabase()
: super(FlutterQueryExecutor.inDatabaseFolder(
path: "db.sqlite", logStatements: true));
int get schemaVersion => 1;
Future<List<Order>> getAllOrder() => select(orders).get();
Stream<List<Order>> watchAllOrder() => select(orders).watch();
Future insertNewOrder(Order order) => into(orders).insert(order);
Future deleteOrder(Order order) => delete(orders).delete(order);
}

3. Generated file code

https://gist.github.com/anmolseth06/8115030632c51f498a4cd393e777d192#file-moor_database-g-dart


User Interface

  1. User Input Widget
TextField(
decoration: InputDecoration(hintText: 'Product Name'),
keyboardType: TextInputType.text,
controller: productNameController,
),
TextField(
decoration: InputDecoration(hintText: 'Product Price'),
keyboardType: TextInputType.number,
controller: priceController,
),
RaisedButton(
onPressed: () {
setState(() {
AppDatabase().insertNewOrder(Order(
price: priceController.text,
productName: productNameController.text,
));
      priceController.clear();
productNameController.clear();
});
},
color: Colors.green,
child: Text("Place Order"),
),

We are using setState state management to control the state of the widgets.Onpressing the Raised Button price and productName are made equals to the priceConroller and productNameController.

.text converts the TextEditingController() to text

2. ListView of Orders

This widget contains the list of all the orders that the user provides using the UserInput widget.

StreamBuilder is used to listen to the stream watchAllOrder().

ListTile contains a CircleAvatar, title, subtitle, and trailing.

snapshot.data is the list of all the Orders that are fetched from the local database.

StreamBuilder(
stream: AppDatabase().watchAllOrder(),
builder: (context, AsyncSnapshot<List<Order>> snapshot) {
return ListView.builder(
itemBuilder: (_, index) {
return Card(
color: Colors.orangeAccent,
child: ListTile(
leading: CircleAvatar(
child: Text('${index + 1}'),
radius: 20,
),
title: Text(snapshot.data[index].productName),
subtitle: Text("Rs. ${snapshot.data[index].price}"),
trailing: IconButton(
icon: Icon(Icons.delete_outline),
onPressed: () {
setState(() {
AppDatabase().deleteOrder(snapshot.data[index]);
});
},
color: Colors.red,
)),
);
},
itemCount: snapshot.data.length,
);
},
),

Full Project

flutter-devs/moor_database_example
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Thanks for reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

If we got something wrong? Let me know in the comments. we would love to improve.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

We welcome feedback, and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸

Flavors In Flutter — Part 1

0

Flavors has always been an Intrinsic part in native applications that can now be achieved in Flutter’s latest stable version which is equipped with key Integral updates & features.They let you define specific build configuration & modify them as you want . Flavors are largely used in large scale apps to ensure the correct deployment of desired version of the app by using different icons, app names which can also be easily switched up .

Android Flavors (or schemes on iOS) are defined by categorising different compile-time configuration build types for different stages of development taking in consideration the version of app the particular team is currently working to get in-lined the maximum effeciency.

Flavor: Same App, Different Behaviour.

Flutter, even in its own possess the different build modes which can be amicably used for different purposes

The different modes in flutter SDK are :-

:: Debug: It is the build mode we most use . A ‘ debug ’ banner is usually shown in the top right when you run this mode which can be easily removed by disabling a bool property debugshowcheckmodebanner.The final apk size of this build mode is large. By default, flutter run compiles to debug mode.

:: Profile: Profile mode usually disabled in emulators and can be checked only for real devices to profile your app’s performance .Tracing and service extensions are enabled.Use command flutter run — profile in the terminal for execution.

:: Release: Release mode is the one with most optimal and minimal sized build mode as it is mainly used for deployment. Debugging & Service extensions are disabled. Use command flutter run — release in the terminal for execution.

In Testing, we mostly use flutter release as the app will surely behave much closer to the experience final user will get.

What is the Dire Need to use flavor ::

  • Large scale apps are to be dealt with Caution making flavors a must Use .While dealing with live projects a wrong update may prove to be fatal . Flavors prevent such to happen.
  • Flavors are apparently the Need of the hour as the team may be working in different stages in parallel so the same version may not always be appropriate for the whole team.
  • More focus can be laid down at Innovation by experimenting in earlier stages without any hindrance in release mode .

Create a new flutter app

:: Open your IDE — Select new flutter project . Enter project name andthen click Finish .This will install the sdk (if needed) and will create a new project

Creating Dart Flavors ::

Defining Flavours in dart can be easily done with the help of dart file FlavoursConfig.dart:

In FlavoursConfig we declare the flavors’s appname and other functionality specific as per flavour types .

FlavoursConfig ,an Inherited Widget will be used to configure our flavour making it easily accessible throughout the app. Now for each flavor, we create the main.dart file, used to start up the app . Here we have created 3 such main files:

  • development.dart :
development.dart
  • qatesting.dart :
qatesting.dart
  • production.dart:
production.dart

In qatesting.dart , FlavorsConfig created previously can be readily used to define a flavor, a custom color, and some values. The same must be done with development.dart & production.dart

In app.dart , Homescreen is created so that futher app can be made.

Flavor Platform Based Configuration ::

Dart created flavors are quite useful , It may also be worthwhile defining them on the basis of patform helping us in setting up personalised appicon & appname . This needs to be done by modifying android/app/build.gradle adding productFlavors to it :

build.gradle file

The flavourDimesions can be named as per developer ‘s intent but it should be concerned that it shall remain same to all the flavors created up.We have also created applicationIdSuffix as per flavors.

Flavor Based App Names ::

We can also assign different app names to each build flavor as needed.This can be done by creating a file namely strings.xml seperately inside each res directory of specific flavour. We assign a string to the app_name as per our wish though i have listed each string.xml by adding comments of their flavour names below:

This strings need to be referenced in the manifest also which can be passed by assigning parameter to android:label. This need to be referenced at android/app/src/main/AndroidManifest.xml:

With the help of this Different app icons can be constructed :

Using Flavours using IDE:

Though we can always run the different flav our configuration with help of commands at the terminal But It is quite Handy to run flavours from your IDE (Android Studio ) by making custom edit configuration for them as :

:: From the Select panel we can Add/Edit Configuration. Choose Edit Configuration:

:: Select Add New Configuration — This can be done by selection add from the + at left hand corner or by using the shortcut alt+insert .

:: Select Flutter from the dropdown menu .

:: Select a appropriate name in the name menu . At the Data EntryPoint , we need to choose the corresponding main file needed from the Choose Dart File menu. Here , I have taken the name as Development.dart .

In the build flavour , We need to provide the build flavour defined in build.gradle . After Providing this Click apply and Select ok. This will create the configuration sucessfully.

Run different flavours in different flavour mode as by inserting the following commands in the terminal of your IDEs ::

Flavor on DEBUG mode can be run as :

  • flutter run –flavor production-t lib/production.dart
  • flutter run –flavor qa-t lib/qatesting.dart
  • flutter run –flavor development-t lib/development.dart

We can also run the flavour in Profile and Release from the help of terminal as PROFILE mode:

  • flutter run –profile –flavor production -t lib/production.dart

RELEASE mode:

  • flutter run –release –flavor production -t lib/production.dart

If Felt stuck between running multiple flavors , Ensure running flutter clean to clean build files created by app time-to-time.

Closing Thoughts

Flavors is a Quintessential tool in large scale apps in native applications which has now also been introduced in flutter’s latest version also .This basically ensures deployment of the rightly version of the app & decrease in development time by preventing any undesirable errors to occur.

If you have not used Flavors, I hope this article has provided you with valuable information about what is all about Flavors, and that you will give it Flavors — a Try. Begin using flavors for your apps !!

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:

And read more articles from FlutterDevs.com

FlutterDevs has been working on Flutter from quite some time now. You can connect with us on Facebook and Twitter for any flutter related queries.

We welcome feedback, and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸

www.flutterdevs.com

Using Firebase Firestore in Flutter

0

Introduction

In this post, we shall discuss the cloud firestore. We will learn about the various curd operation with the firestore. If you want to store the data locally inside your app you can read my post on the moor library.

Link :

Moor in Flutter
MOOR is a library allowing us to work with the Flutter’s SQLite database fluently and in pure Dart…medium.com


Table of content

  1. cloud firestore vs realtime database
  2. Setting up the project.
  3. Adding required dependencies.
  4. Creating a collection on the cloud firestore.
  5. Uploading data.
  6. Fetching data.
  7. Deleting Data
  8. Updating Data
  9. Designing the UI.

Cloud firestore vs Realtime database

  1. It provides us more structural data.
  2. This database is scalable.
  3. East to fetch the data.
  4. Multi-region support.
  5. Range of pricing model.
  6. Data validation happens automatically.

Setting up the project

How to integrate firebase with flutter android or ios app ?

  1. Open firebase, click on get started which will take you to the Add Project screen.
  2. Enter the project name and complete the other essential steps. It will take you to your project screen, click on the android icon.
  3. Now the steps which are coming are very important so please do them very carefully. You have to enter the package name which is generally your application Id in your app-level build.gradle file. Add the other two optional fields if you wish to add them as well.
  4. Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory. (NOTE: Please check the file that you have downloaded has a google-services.json name or not because if you download it more than one time the name of the file changes to google-services(2).json, so please remove (2) from the file name or rename it to google-services.json)
  5. You will see the following screen.

Here the first block contains the classpath that you have to add to your project level build.gradle file under the dependencies section. The second section contains a plugin and dependencies that you have to add to your project app-level build.gradle file. Please add these lines properly and carefully if you are adding them for the first time.

Left: project/build.gradle ….Right :project/app/build.gradle

6. Now you should restart your application (NOTE: Please refer to full restart not hot reload). Wait for few seconds and your application will be successfully added with firebase. If you see the bellow screen on your firebase then you have successfully added firebase to your app…


Adding required dependencies

We will require the following dependencies

dependencies:
cloud_firestore:

Also, import the package to your file.

import 'package:cloud_firestore/cloud_firestore.dart';

Please add these line in your app/build.gradlemultiDexEnabled true to your defaultConfig section and also add implementation 'com.android.support:multidex:1.0.3' to the dependencies section.


Creating a collection on the cloud firestore

  1. Click on start collection and enter the Collection ID.
  2. Enter the field name with type and value.

Here I have created a collection of products that contain two documents and it has four fields i.e productName, productPrice, imageUrl, isFavourite. You can customize them according to your requirements.


Uploading Data

To upload the data on the firestore we need to create a firestore instance.

Future<void> uploadingData(String _productName, String _productPrice,
String _imageUrl, bool _isFavourite) async {
await Firestore.instance.collection("products").add({
'productName': _productName,
'productPrice': _productPrice,
'imageUrl': _imageUrl,
'isFavourite': _isFavourite,
});
}

Here I have declared an async function that takes two arguments as parameters.

collection() statement takes the collection name that we have initialized in our cloud Firestone.

.collection("students")

Fetching Data

We need a stream that will control the flow of data from the database to our app.

stream: Firestore.instance.collection("products").snapshots(),

collection() statement takes the name of a collection that we have created in the previous section.

To implement the stream we require a StreamBuilder.

StreamBuilder(
stream: Firestore.instance.collection("products").snapshots(),
builder: () {},
);

StreamBuilder builder takes the context and the snapshot.

StreamBuilder(
stream: Firestore.instance.collection("products").snapshots(),
builder: (context, snapshot) {},
);
builder: (context, snapshot) {
return !snapshot.hasData
? Text('PLease Wait')
: ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot products =
snapshot.data.documents[index];
return ProductItem(
name: products['name'],
imageUrl: products['imageURL'],
price: products['price'],
discription: products['description'],
);
},
);
},

products is a DocumentSnapshot, which we will use as an entity to access the various field.

DocumentSnapshot products = snapshot.data.documents[index];

snapshot.data.documents.length is the length of documents that we have created in our database.

itemCount: snapshot.data.documents.length,

We are returning a Text if the data is under the fetching process and if the data is loaded from the database then we build a ListView.builder which returns a ProductItem() widget.


Deleting Data

Deleting the data require a DocumentSnapshot to excess the documentID of the specific collection. It also requires the collection name.

Future<void> deleteProduct(DocumentSnapshot doc) async {
await Firestore.instance
.collection("products")
.document(doc.documentID)
.delete();
}

Editing Data

Editing the data require the id of the document and the name of the collection.

It also requires the updataData() statement which takes the fields that are needed to be updated.

In this particular case, I am updating the favorite feature of the app.

{"isFavourite": !_isFavourite}

Here every time the user press the favorite its value will be updated to its opposite value.

Future<void> editProduct(bool _isFavourite,String id) async {
await Firestore.instance
.collection("products")
.document(id)
.updateData({"isFavourite": !_isFavourite});
}

All Operation

operation.dart

https://gist.github.com/anmolseth06/ac4b329e2ce1f3eba8adda734c21b50b#file-operation-dart


Designing the UI

homePage.dart

https://gist.github.com/anmolseth06/b5a609b6b159fcad834ae86e88b8e2a3#file-homepage-dart

Product Widget

https://gist.github.com/anmolseth06/41ccc95ef240ac1f89508153b73c0e70#file-productitem-dart

Adding Product Screen

https://gist.github.com/anmolseth06/a601b9246e4474ec1b92bfa0b26e8176#file-addproduct-dart


Full Project

flutter-devs/firestore-Database-Demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Thanks for reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

If we got something wrong? Let me know in the comments. we would love to improve.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸

Design Patterns in Flutter- Part 1(MVC)

0

Design Pattern is something which has been always a very Mysterious term for developers and we are very much confused between the term Software Architecture and Design patterns, So before starting anything about design patterns we need to clear this doubt regarding the Design Pattern and Software Architecture.

Software Architecture

Software Architecture is how the whole components of system software are organized and assembled. How they communicate with each other. And the Constraint the whole UI is ruled by.

So If we go through this definition we come across three important aspects and those are

  • How the whole components of system software are organized and assembled:- Architectural Pattern
  • How they communicate with each other:- Messaging & APIs
  • The constraints the whole UI is ruled by:- Quality Attributes

Design Pattern

Design Pattern could be defined as a common repeatable solution to recurring problems in software design. Design patterns can not be related to a finished design which will be directly used in code but it could be understood as a description or template for how to solve any common problem that may occur in many situations.

So If we go through this Definition we will find that

  • It is a solution to recurring problems of software development.
  • It is not a sample code which will be directly used in the project.
  • It is just a template that helps to solve any problem that occurs in software development.

Difference between Software Architecture and Design Pattern

So after going through both the definition we came to know that both of it could be differentiated on the basis

Scope:- Software Architecture has a universal scope, it has to managed at a Higher level like Server Configuration, etc.Whereas Design pattern has a Lowe level scope that comes to the project internal code pattern.

Working:- Software Architecture is all about organizing and assembling the components in such a way that their communication is very much convenient and secure. Whereas a Design pattern is about how the components are built.

So I hope this comparison clears the doubt between Software Architecture and Design Pattern. So after having a piece of knowledge that what design pattern actually we will start a few famous design patterns which are mainly used in flutter development. So, First of all, we will start with the very Basic MVC Pattern and we will see how MVC is used in Flutter.

MVC In Flutter

MVC stands for the model view controller and its main work is to have a segregated code base, it aims to separate the code and area of responsibility while software development. The main focus of MVC is to separate the interface of the project from the functionality and the data that is used in the application. As we all know that neat and arranged things are always easy to use and maintain, the same is with MVC it makes the codebase neat and arranged and it achieves these with three of its components.

  • Model:- Model compromises of the data source it may be from anywhere DB, API, JSON, etc. In some cases, it may consist of some business logic.
  • View:- View is all about the user interface, I.e displaying data and taking inputs from the user.
  • Controller:- It contains the business logic, I.e Controlling what data will be shown to the user, user input handling, etc.

Communication Flow

Differentiating the three of these basic components of projects helps the developer to write a neat and modular code which makes the code Reusable and also helps in parallel development. It becomes very easy to work on the project as it does not affect other parts of the project if something is changed in one part. So keeping them separated needs a communication flow in which they will interact with each other and achieve the functioning of the project.

So as we could see from the following flow diagram the User interacts with the View part of the project which helps the user to see the Data and provide the input to the controller through the view. Controller Active as the brain of the project does the calculation or manipulation of data from the user or takes the data from the model to work on it and provides it to the View which shows the desired data to the user. Here we find that the View shows and receives the data but it directly not interact with the Model, it is the controller that plays a role between view and model in data manipulation and data representation. The View and the Model are tightly coupled to the Controller i.e View Knows how to communicate to Controller, Controller knows how to communicate to Model and Model and View works collectively without knowing each other existence.

Code Understanding:

If you have not installed the flutter SDK or you are still getting familiar with it :

/media/eaefff34fddcc032a2b4fe36aa69b8a9

Let’s dive into the code part for an In-depth understanding of the process:-

1. Firstly, Create a new project and then clear all the code in the main.dart file. Type below command in your terminal:-

flutter create yourProjectName
  • Add the current latest version of MVC pattern package under the dependencies in pubspec.yaml file.
dependencies:   
mvc_pattern: ^latest version

Create a Model Class:

As Explained above a model class is created for both counter:-

Create the Main Controller :

The Controller is Created as this Basically Ensures the interaction with the model :

Adapting it Into The View :

The controller is then bound to the view.dart file so that the increment and decrement functionality may work as depicted.

Find the Code Version on Github at:

flutter-devs/Flutter_MVC
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com

Closing Thoughts

Design Pattern is a Quintessential tool in large scale apps in native applications which you can also practice in flutter also. In this Blog, only MVC has been explained but this will a series of blogs and in the next blogs, we will be sharing about MVP, MVVM, CLEAN, etc.

If you have not used Design Patterns in Flutter, I hope this article has provided you with valuable information about what is all about it, and that you will give it Design Patterns — a Try. Begin using them for your Flutter Apps !!

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:

And read more articles from FlutterDevs.com

FlutterDevs has been working on Flutter for quite some time now. You can connect with us on Facebook and Twitter for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸

CI/CD with CodeMagic | Flutter

0

These days approaches for code delivery are gradually changing when writing quality code and the fine product delivery is a need of the time and in this situation, developers find themselves in the dilemma to manage both things at the same time but now this is not a big deal because of CI/CD(Continuous Integration/Continuous Delivery). So let’s first know about CI/CD.

What is CI/CD

It can be easily understood by its name Continuous Integration/Continuous Delivery and it is the process to directly merge your product version(code) into the main branch of your code and also helps to get builds of the product on the daily basis and also look after the integration problems, CI helps to trigger the build whenever code is pushed and integration tests make sure that the new part which has been added to the application does not break the previous build of the application and if the test or the build fails then ensure that the app remains stable, While CD is Continuous Deployment or Continuous Delivery is the automatic deployment of an app (to production).

Now let’s understand how to implement it

There are various ways to implement CI/CD and we are going to get it done by using Code Magic. It was launched at Flutter Live in December 2018 in cooperation with Google, Code Magic provides various options to implement CI/CD.

You can log in with any mentioned account, and now I am going to implement it by using GitHub.

But you should remember one thing your GitHub/Bitbucket/GitLab should have a repository in which you want to implement CI/CD.

After login with any particular account, You will navigate to the home page of code magic.

You will find this kind of screen now you have to choose in which repo you want to implement CI/CD. So here in every repository, you can see a setting icon and “start new build” options so before going to build option first we need to set up our repository for different workflows and many more options are there.

So at first, we click on that icon right before the “start new build” option and you will navigate to this screen.

Here you need to set up different workflows for a different kind of delivery and testing like Default workflow, Dev workflow, QA workflow, so create it by clicking “Duplicate workflow” in ton right side of the screen.

After creating duplicate workflows you can choose which workflow you need which type of customization (as shown in the above screen).

You also need to implement the same branches in your repo and that could be master, QA, dev.

So every time you need to push your code from dev (it is your choice) and then you need to merge changes into different branches in your GitHub.

After that, you need to select different workflows one by one and customize the setting according to your need, and I started the customization from Dev workflow and the first option I found to customize is “Build triggers”.

Here I have clicked on triggered on push, so every time we push over code over GitHub we will get a new build, you can choose different options according to your need for different workflows.

After that, we move to the next option below it where we would make some changes and this is “Test”.

As you can understand by seeing it, if the test fails, it automatically stops build.

Next option is “Build

In this, you can select the flutter version, platforms, in which mode you want to release your app,

and the next part is ‘Publish,

here you can select you to publish options like where you want to share your build or changes, even you can update your app in play store and apple app store directly and for this, you only need to fill some info by clicking on Android code signing and iOS code signing, you can share your build over email by providing mail addresses directly.

After all these customizations you need to click on “start new Build” top of the page and you will navigate to this page

here you can select your branch your workflow and by clicking on which type of build you want you can move forward. when you click any of the options you will find that it started creating a new build for every platform you selected during customization

and after completing its build you will receive builds on all platforms you selected. So here is the image of my mail inbox where I received a mail of new build now I can download Apk and test if the new changes are working fine or not.

So this was the small introduction of CI/CD through code magic.

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us
And read more articles from FlutterDevs.com


FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

CI using Bitrise in Flutter

0

Flutter has been out there from a long enough time and has been taking the Mobile Development Community by Storm. With the scope of Mobile Development apparently increasing ,the need to Integrate CI/CD Tools in your flutter Apps is a Must enriching the work pattern of Team. One of the prominent among Continuous Integration is Bitrise.

Continuous Integration:

Continuous Integration is the process of merging and syncing your code to one dedicated git provider and automating your build process upon performing the tests. The software development process is to make your development flow smoother and keep your code clean when working in a big team code merging often ends up in issues. Continuous integration is about making sure that every change is merged into one dedicated branch upon task completion and to get a corresponding build for the same.

CI using Bitrise:

Bitrise is cloud-driven CI/CD tool which has four major points as described by them:

Complete mobile development stack inclusion:

Bitrise promises support for both native as well as cross-platform, be it Java or Kotlin, Objective C or Swift, or Iconic, React or Flutter it got you all covered.

Code independence:

Whether you have your code on Github or on Bitbucket or on GitLab or on it’s private or public git service. It will get your code for you.

Hardware independence:

Since Bitrise is a cloud-driven tool you don’t need any specific hardware to make this work. All you’ve to do is just add your app to their dashboard and voila!

Build anytime:

Webhooks works on pull-request and every time a request is made the webhook gets triggered or makes a custom webhook or schedule your builds.

Let’s Start

Now, that we have had an idea about continuous integration and about Bitrise lets integrate Bitrise to our Flutter app.

Step 1: Setup your application

  • Create a basic app or choose an already existing one.
    I am going to start with the basic demo app just to give you the idea of Bitrise integration.
  • Create Flavors for your app.
    Now, I won’t go in detail about how to setup Flavors for your flutter app, for that please follow this Creating flavors of a Flutter app and Flutter Flavoring. But adding Flavors to your app is like setting it right for different build requirements. In an organization, it’s always a good practice to create flavors for your app, where you might handle different build instances for different purposes, one for Demo purposes, one for Dev, one for Staging, one for Production and every build might have different configurations, different icons, different names so with the use of flavors it gets easy to handle all these scenarios.
build.gradle:app/Android

The above-mentioned articles will help you create flavors for your flutter app for both platforms.

Step 2: Integrate your App to Bitrise CI

Now, that you’ve created flavors for your app, you can head over to Bitrise and sign up on the website or log in if you already have an account.
Once you’re in the dashboard, click Add new application. This is where you’ll integrate your App to Bitrise after following the steps.

Procedure to integrate apps into Bitrise.

Now we’ll look into these steps:

  • Choose Account
    Here, you choose your Bitrise account to which you want to add the app. Once you’ve chosen your account you’ll be required to select the privacy of your app, of the two options available i.e Private and Public. Private is for you and your team members while the Public is for everyone.
  • Connect your repository
    Now, that you’ve selected your account and the privacy mode for your app you’re asked to select the repository for the source code of your app. There’re various options like GitHub, Bitbucket, GitLab or git URLs where the source code of your app already exists.
  • Adding an SSH key to your repository
    Now, that you’ve selected your repository you may need to give it access rights to Bitrise by integrating the SSH key to the repository, this is required for Bitrise to clone your code to their virtual machines. For this, you have two options, Automatic integration or Manual integration.
    When you select the Automatic option among the two on the right top corner of the step, an auto-generated key will be registered for Bitrise and corresponding public key for your Git provider. The Manual option lets you generate your own SSH key and register them to Bitrise and to your Git provider.
  • Choose the branch
    Select the branch of your repository from which the Bitrise will fetch the source code.
  • Build configuration
    After selecting the branch Bitrise will clone and validate it and upon validation, Bitrise will ask you to select the build config of the app which and to select the tests if available in your app which we created while setting up the app. 
    There are two ways of doing this, Manual and Detected. In Manual mode, you can select the build configuration as per need while in Detected mode, Bitrise detects the existing config.
  • Select the App icon
    Select the app icon which you want you to use for your app if you have or you can skip this step for now.
  • Register a webhook
    So, you have almost added your app to Bitrise but there’s one finest and the best thing about CI’s i.e automation. I mean isn’t why we here after all? To make sure that the moment we make some changes in the code and as soon as we finish pushing the changes to the git provider Bitrise automatically tests the build and send us the build? That’s what this Webhook will do. It will keep an eye on the branch you’ve provided in the above steps for any push-requests, following which it will update its code and run the test setup by you and upon any kind of response either Build Successful or Build failure, a feedback mail to your registered mail id.
    This step is not mandatory as you can find this step later in the settings page so feel free to skip it.
  • Almost DONE!
    So, if you followed all the above steps correctly, rejoice! you’re almost done. Bitrise will automatically trigger a build for you and as soon as its completed you’ll be notified about it in your mail.

Bitrise Dashboard

Once your app is added to the Bitrise an initial build will kick off automatically and the report for the following will be mailed to you by Bitrise. Now, if you check the dashboard, on the right corner you’ll find your apps added to Bitrise. On clicking on it you’ll be navigated to the detail page where you can access the app workflow, builds, code, settings, etc.

App Detail Interface
  • Builds
    This will have all your build reports.
  • Workflow 
    This contains the nuts and bolts of your app for Bitrise integration. You can edit or create workflows as per your requirement, you can sign your app for deployment to the play store or app store, edit/create environment variables that are used in in the flow, “bitrise.yaml” file is the config file that fetches all the configuration of your app on Bitrise.
  • Team
    This will let you control your team members related to this current app/project. You can assign the Admin, Developer, Tester, all that sort of work.
  • Code
    This lets you control the trigger token and webhooks for your app.

Conclusion:

I hope you got an idea about how to work with Bitrise in Flutter. Well, there are various options out there for CI and sometimes it’s not about which is best, it’s also about what you feel comfortable with. So, you’re all ready to explore further but all these tools are efficient only if your app/project is of enterprise-level when a number of people are working as a team on a common app/project and if you’re a sole developer you don’t want to go through this hassle.

flutter-devs/flutter_bitrise
A flutter demo showing use of flutter bitrise. Contribute to flutter-devs/flutter_bitrise development by creating an…github.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

Hive NoSql Database

0

For those who don’t know about NoSql?

NoSQL, which stands for “not only SQL,” which is an alternative of traditional relational databases in which data is placed in tables and data schema is carefully designed before the database is built. NoSQL databases are especially useful for working with large sets of distributed data.

What is Hive?

Hive is a lightweight, NoSQL database, easy to implement and also having high benchmark on the devices and written in the pure dart. Until and unless you need to model your data with many relationships, in that case it recommended to use SQLite.It has no native dependencies (it runs on Flutter Web!) can be the best option. Hive supports all platforms supported by Flutter.

Hive having the concept of boxes(which store data). A Box has to be opened before use. In addition to the plain-flavoured Boxes, there are also options which support lazy-loading of values and encryption.

What are Boxes?

All data stored in Hive is organized in boxes. A box can be compared to a table in SQL, but it does not have a structure and can contain anything. For a small app, a single box might be enough. For more advanced problems, boxes are a great way to organize your data. Boxes can also be encrypted to store sensitive data.

Before you can use a box, you have to open it. For regular boxes, this loads all of its data from the local storage into memory for immediate access.

var box = await Hive.openBox<E>('testBox');

To get an already opened instance, you can call Hive.box('testBox') instead. It doesn’t matter though if you try to call openBox multiple times. Hive is smart, and it will return an already opened box with the given name if you’ve previously called that method.

To prevent holding unnecessary data in memory, you can close the box when you are done with your box. Don’t worry if you forget to close the boxes . Smarty Hive do it for you. Its also has a handy method for closing all the box.

Hive supports all primitive types, List, Map, DateTime, BigInt and Uint8List. Any object can be can stored using TypeAdapters.

In this, we are covering how to save a custom object(Employee)showing Basic CRUD operations:

Adding Dependencies:

dependencies:
flutter:
sdk: flutter
  # The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons:
hive: latest version
hive_flutter: latest version
path_provider:

dev_dependencies:

flutter_test:
sdk: flutter
hive_generator:
build_runner:

Initializing and Registering Adapter:

Box _employeeBox;

@override
void initState() {
super.initState();
Hive.registerAdapter(EmployeeAdapter());
_openBox();
}


void _openBox() async{
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
_employeeBox = await Hive.openBox('employeeBox');
}

Under the hood, Hive works with binary data. It cannot recognise it

Box boxObject = await Hive.openBox('employee');
boxObject.add(Employee("paras" ,62));

its throws exception. or we save this by making it TypeAdapter.

import 'package:hive/hive.dart';
part 'employee.g.dart';

@HiveType(typeId: 1)
class Employee {

@HiveField(0)
final String name;

@HiveField(1)
final int id;

Employee(this.name, this.id);

}

And in Terminal type :

flutter pub run build_runner build part ’employee.g.dart

and you are done. This will generate you a TypeAdapter.

Save (Add)

We open the Box at the time of Initialization.

_employeeBox.add(Employee(employeeNameController.text, employeeHobbyController.text));

To show saved data in List (READ)

ListView.builder(shrinkWrap: true,
itemCount: _employeeBox.length,
itemBuilder: (context ,index)
{
final employee = _employeeBox.get(index) as Employee;

return Container(
margin: EdgeInsets.symmetric(vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text("${employee.name}",style: TextStyle(fontWeight: FontWeight.w400 ,fontSize: 15),), Text("${employee.hobby} ",style: TextStyle(fontWeight: FontWeight.w400 ,fontSize: 15),),
],
),
);
},)

For Updating and Deleting we use putAt() and deleteAt().

Link for repository:

https://github.com/parasarorahere/Hive-Database.git

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us
And read more articles from FlutterDevs.com


FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

Push Notification In Flutter | FireBase

0

Google recently announced that more than over 2 million Developers Worldwide have laid their hands on Flutter. After the language’s roll-out at the Google I/O ‘18, This revelation from the search giant immensely Signifies diversion of developers from Native development to the Newer Technologies Building Extensive Cross-Platform Apps. Flutter started its life as an open source UI framework that helps developers build native interfaces supporting different device sizes, pixel densities & orientations creating magnificent digital experience.

In this Article ,We will have a look at How to send Push Notification in a Flutter project through the help of firebase its features and customisation available:

Introduction to Push Notification:

Push Notification is a Infallible medium of alerting app users of Information they might have opt-in from apps and services . It is also a prominent retention medium to drive User-Engagement for the apps that might have gone Unnoticed after their being Installed .

Firebase Cloud Messaging (FCM) avails a comprehending set of online tools to send notifications to the user audience intended . You can always select your target audience for the push notification on the basis of firebase predictions to dynamically segment your user & the engagement you’re trying to recieve by always keeping in sight of their relative number from the total user base. We Intend To learn Sending messages to a flutter app and the role of back-end cloud function & firebase analytics in their being broadcast notification to a Single User|Segmented Audience creating a pipeline for Push Notifications.

FCM push notifications can be comprehended to be of three types:

: Token Based Notification- This can be sent with help of user device token for sending notifications on the basis of Individual User Activities .

: Topic based Notification- This kind of Push Notification is sent for subscription based notification to the users that user might have opted-in .

: Segment based Notification : Sending Notification on the basis of firebase analytics to a segment of your user .

Firebase Cloud Messaging Project Creation

In order to send Push Notification ,We need to create a firebase project for the Firebase Cloud Messaging from firebase.google.com by logging in with your google account. This brings us to the following screen::

Add project at Firebase Console

Click on Add Project Button (+) initiating firebase project creation process.

Mention Name of project

Select the appropriate name for the project entering continue further

select analytics (if needed )

You can either select the firebase analytics and then clicking on Continue Project. Firebase messaging is now created and ready to use .

Firebase project created

This Progress indicator will show before the dashboard indicating success.

Dashboard Screen

In the project overview page, click the iOS icon to launch the setup workflow as we now needs to register your flutter project for the android and iOS application. .

Integration with iOS App

Enter iOS Bundle ID

Enter the iOS bundle ID which can be founded also at info.plist of being the next line after CFBundleIdentifier.

Make sure you enter the correct ID As this can’t be edited further at the moment .

Download GoogleService-Info.plist

Next step , We need to download the config file named as GoogleService-info.plist & repeating the similar process to register your android app there savoing the Google-service.json file .Keep those configuration files in ready-to-use with Flutter app later.

Click Project setting from the option further. Select Cloud messaging noting down the server key signified there.

Flutter Application Setup with FCM

Create a new Flutter Project making sure application name is same as package or bundle ID at the time of firebase project creation

Open pubspec.yaml entering the firebase messaging dependencies :

dependencies:
firebase_messaging:           <add-latest-version>
device_id: <add-latest-version>

Android-specific configurations

: Open build.gradle of android section. In the dependencies section add :

dependencies {classpath 'com.google.gms:google-services:4.3.3'}

: Open android/app/build.gradle . In the dependencies section add the following & In the end enter the required plugin as shown up:

dependencies {
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-messaging:20.1.5'
}
apply plugin: 'com.google.gms.google-services'

Add the following intent filter inside of the activity element of your AndroidManifest so that when user taps in Content is Being Displayed.

<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Add the google-services.json file previously downloaded by putting the file in android/app of your project file folder.

iOS Specific Configuration:

We need to register our app seperately in the firebase project for its configuration for iOS apps:

: In Xcode , Open ios/Runner/Runner.xcodeproj and check whether the Bundle identifier at general section is same from the Bundle Id entered at the Project , otherwise edit this to make them similar and Register.

: Enter the Downloaded GoogleService-Info.plist from the firebase console into Xcode project within Runner:

Important Note: Do not just copy the folder without the help of Xcode by simply copy-pasting outside of Xcode as this will likely not work

Adding Firebase SDKs

  1. Create a Podfile if you don’t already have one:
$ cd your-project-directory
$ pod init

2.Install the pods, then open your .xcworkspace file to see the project in Xcode:

pod install
open your-project.xcworkspace

3. Initialize Firebase in your app:

Import the Firebase module in your UIApplicationDelegate

import Firebase

Configure a FirebaseApp shared instance, typically in your app’s application:didFinishLaunchingWithOptions: method:

// Use Firebase library to configure APIs
  FirebaseApp.configure()

FCM Notification Types:

  1. Individual Device Token Based Notification : Personalised notification are most used for sending Push Notification as they are more apt and specific to Key needs of the user being sent on the basis of analytical methods . Though they are being sent mostly in the form of Cloud Functions but you can also send them from the firebase console which is depicted below:

In the Grow Section , Select Cloud Messaging option after this you will see a prompt to Send your first message

Cloud Messaging

Enter the Notification title & description text . We can also add the Notification Image as depicted . Before Sending the notification message a user can always preview the notification in (expanded & Initial state) the notification will likely be shown on devices.

Individual Push Notification

The only thing needed right now to send the notification is the device token which can be availed by using the device_id plugin at the dependencies:

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

@override
void initState() {

super.initState();


Future.delayed(Duration.zero, () {
this.firebaseCloudMessagingListeners(context);});}

void firebaseCloudMessagingListeners(BuildContext context) {
_firebaseMessaging.getToken().then((deviceToken) {
print("Firebase Device token: $deviceToken");

});
}

Device token obtained from the flutter code can be entered for the push notification enabling device specific Push Notification.

Device token

2. Segmented User Based Notification: Segmented notification are sent on the basis of various factor : country, last app engagement , user audience . Firebase Prediction Tools comes out handy for this making possible by studying your app’s analytics helping you in driving campaign driving better user engagement.

: After Successfully Entering the Notification Details . You need to select the segment of user audience on the basis of various tools alongwith firebase prediction that use your analytics to drive user campaign most suitable .

Segmented Push Notification

You will then see the preview for the segmented notification . Publish here for successfully sending of the notification.

Preview

3. Topic based Notification: Topic based notification are another personalised way of sending notification that may have opted in for a particular services . This can be done either in the background or by manually making the user subscribing to a service offered.

MaterialButton(
child: Text('Subscribe to FlutterDevs'),
onPressed: () => _fcm.unsubscribeFromTopic('FlutterDevs')
),

Here, If the User taps on the button will result in him subscribing to the topic FlutterDevs which maybe later used for sending notification on the topic .

This will result in sending notification to the subscriber of ‘FlutterDevs ’ topic.

preview

All Push Notification were recieved to the Intended Users:

Closing Thoughts:

We have Surely realised the Importance of Using Push Notification for our mobile apps quite apparently and It’s Integration with Firebase really Alleviates the problems of many apps getting unnoticed after being installed being a great retention medium for them .Firebase facilitate multiple services collection availed at a single place such as storage, cloud functions, real time databases, authentication. Hope After reading the article you must have gotten an insightful of Push Notification in Flutter with Firebase. Give it a TRY!!


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:

And read more articles from FlutterDevs.com

FlutterDevs has been working on Flutter from quite some time now. You can connect with us on Facebook and Twitter for any flutter related queries.

We welcome feedback, and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸

www.flutterdevs.com

UI Testing in Flutter

0

Introduction

In this post, we shall discuss about the flutter UI testing. Testing the UI of the app is an essential part of a developer side. It ensures the developer that the code is working in the required widget tree or not.


Table of content

  1. Flutter Driver
  2. Adding dependencies
  3. Adding files
  4. Methods in Flutter Driver class
  5. Flutter driver element identification
  6. Enabling the flutter driver
  7. Writing the test
  8. Run the test

Flutter Driver

Flutter driver is a class that creates a driver that uses a connection provided by the given serviceClient, _peer, and appIsolate.

It is very similar to testing frameworks such as Selenium WbDriver, Protractor, Google Espresso.


Adding dependencies

Integrate your flutter app by adding flutter_driver dependency.

Edit your pubspec.yaml file.

dev_dependencies:
flutter_driver:
sdk: flutter
test: any

Adding Files

Create a folder test_driver and add two files in it app.dart and app_test.dart.

app_name/
lib/
main.dart
test_driver/
app.dart
app_test.dart

Method in Flutter Driver class

There are 33 methods in the flutter driver class till now.

Some of them are discussed below…

  • checkHealth

This method checks the status of the Flutter Driver extension.

This method return tow values.

  1. HealthStatus.ok
  2. HealthStatus.bad
  • clearTimelime

This method clears all the timeline events recorder.

The timeout argument causes a warning to be displayed to the user if the operation exceeds the specified timeout.

  • close

Closes the serverClient and _peer.

  • enterText

This method enters a text into an inputField that is currently focused.

  • forceGC

Force a garbage collection run in the VM.

  • getBottomRight, getBottomLeft, getCenter, getTopRight, getTopLeft,

Return the point at the specified location of the widget identified by the finder.

  • getText

This method returns the text in the Text widget located by the finder.

  • requestData

It sends a string and returns a string.

  • screenshot

Takes a screenshot of the event.

  • tap

This method taps the widget located by the finder.

  • waitFor

Waits until the finder locates the widget.

For more info please visit this link.


Flutter driver element identification

There are 4 methods to identify the element in flutter.

  1. bySemanticsLabel()
  2. byTooltip()
  3. byType()
  4. byValueKey()

Enabling the flutter driver

app.dart file

import 'package:flutter_driver/driver_extension.dart';
import 'package:fluttertest/main.dart' as app;

void main() {
// This line enables the extension.
enableFlutterDriverExtension();

// Call the `main()` function of the app, or call `runApp` with
// any widget you are interested in testing.
app.main();
}

Add the following code into your app.dart file

This will enable the flutter driver and call the runApp method.

Writing the test

Writing the test involves the four steps…

  1. Create SerializableFinders to locate the widgets.
  2. Connect to the app.
  3. Test the scenarios.
  4. Disconnect the app.

Create SerializableFinders to locate the widgets.

final writeDataFinder = find.byValueKey("write_data");
final addDataFinder = find.byValueKey("add_data");

Connect to the app

// Connect to the Flutter driver before running any tests.
setUpAll(() async {
driver = await FlutterDriver.connect();
});

Test the scenarios

test("check health", () async {
Health health = await driver.checkHealth();
print(health.status);
});
test("flutter drive test", () async {
await driver.tap(writeDataFinder);
await driver.enterText(dummy_data);
await driver.tap(addDataFinder);
});

In the first test, we are checking the health of the flutter driver extension.

In the second method, we are testing our flutter widgets using SerializableFinders.

Disconnect the app

tearDownAll(() async {
if (driver != null) {
driver.close();
}
});

app_test.dart

https://gist.github.com/anmolseth06/2c11d58bef1860276ca7b05d533a0e81#file-app_test-dart


Run the test

Run the following command in your terminal window…

flutter drive --target=test_driver/app.dart

This command builds and launches the target app and runs the app_test.dart in test_driver/ folder.

Github Link

flutter-devs/Flutter-UITesting-Demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Thanks for reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

If we got something wrong? Let me know in the comments. we would love to improve.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

We welcome feedback, and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸