Google search engine
Home Blog Page 45

Flutter Testing: Let’s Observe

0

Flutter automated testing enables you to achieve higher responsiveness in your app because it helps to find bugs and other issues occurring in your app. It is also important in other perspectives like credibility as a developer.

Here comes a question which may come to your mind:

How can you know if your app is working or not if you have changed or added any features? And the answer is by writing test cases. So let’s understand how to do it.

We have 3 different testing features available

  1. Unit Test
  2. Widget Test
  3. Integration Test

Unit Tests

A unit test can be understood by its name, in the Unit test we test small parts of our code like single function, method or a class and it is very handy to do. It can be implemented by importing test package and if you want additional utilities for test flutter_test can be used.

Steps to Implement Unit Testing

  1. Add the test or flutter_test dependency.
  2. Create a test file.
  3. Create a class to test.
  4. Write a test for our class.
  5. Combine multiple tests in a group.
  6. Run the tests.

Till now we have understood how to import dependency so and let’s understand about the project structure

counter_app/
lib/testing_class.dart
test/
unit_test.dart

Now in your project, you can see that there is already a test folder in which we will create our own class for testing,

Let’s create a file testing_class.dart in which we will be multiplying two digits

Now write a class unit_test.dart in the test folder, where we will write this set of code, in this file there is a main() function and inside this function, we will write code for testing, as you can see in the “test” method object of testing class has been created and with the help of reference variable method of the testing class has been called and we are expecting the output value which should be the exact result.

And to test this code we will run the command(given below) in the terminal and observe the output of this.

flutter test test/widget_test.dart

Now let us understand the testing with the help of Mockito

Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.

Here we are going to understand how can we implement it.

Let’s understand it step by step

Create a simple project then delete the sample code from the main.dart file. then fix all the errors of class.

import 'package:flutter/material.dart';
import 'package:flutter_test_demo/home_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}

Now we are going to test our HTTP request and for this, we are using JSONPlaceholder to find the API link then we create a model class by using the response. you can also create it by using different JSON to dart converter sites.

// To parse this JSON data, do
//
// final userInfoModel = userInfoModelFromJson(jsonString);
import 'dart:convert';
UserInfoModel userInfoModelFromJson(String str) => UserInfoModel.fromJson(json.decode(str));
String userInfoModelToJson(UserInfoModel data) => json.encode(data.toJson());
class UserInfoModel {
int userId;
int id;
String title;
String body;
  UserInfoModel({
this.userId,
this.id,
this.title,
this.body,
});
  factory UserInfoModel.fromJson(Map<String, dynamic> json) => UserInfoModel(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
  Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}

Now we have a model class, after this, we need to make a separate class to make requests and get responses and for this, we would implement the most popular technique HTTP in api_provider class.

import 'package:flutter_test_demo/src/models/user_info_model.dart';
import 'package:http/http.dart' show Client;
import 'dart:convert';
class ApiProvider {
Client client = Client();
fetchData() async {
final response = await client.get("https://jsonplaceholder.typicode.com/posts/1");
UserInfoModel userInfoModel = UserInfoModel.fromJson(json.decode(response.body));
return userInfoModel;
}
}

Now its time to create a test class for testing, so we would be creating a file in the Test folder. when you will open this folder you will get an auto-generated file but we will delete this and create our own you can give any name to the file but remember one thing your file name should contain “_test” like api_provider_test.dart because if you don’t write then flutter would not be able to find it as a test file.

Now you need to import a few Packages to complete all the tests.

import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';

Here HTTP package is used to use tools to mock HTTP requests and the flutter_test provides methods for testing.

Now it’s time to create a method for tests in api_provider_test.dart

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';
import 'package:flutter_test_demo/src/resources/api_provider.dart';
void main(){
test("Testing the network call", () async{
//setup the test
final apiProvider = ApiProvider();
apiProvider.client = MockClient((request) async {
final mapJson = {'id':1};
return Response(json.encode(mapJson),200);
});
final item = await apiProvider.fetchData();
expect(item.id, 1);
});
}

Here in the main() function we write the test method in which first we give a description of our test then we create the object of that api_provider class and by using its reference variable we will change the client() object into MockClient() actually MockClient is a package provided by ‘package:http/testing.dart’ which imitates an HTTP request instead of real request to the server as you can see in the above code.

In HTTP calls we make requests and get responses and we have already defined requests here.

apiProvider.client = MockClient((request) { });

And then we create response objects in this MockClient function

final mapJson = {'id':1};
return Response(json.encode(mapJson),200);

Here you can see the response object is returning the JSON object which is the body of the response and the second object is status code which is the success code of the response then we call the fetchData() which returns UserInfoModel object contains the Key ‘id’ and value “1” or not. Then in the expect method which is provided by test.dart package will compare the result we are expecting from fetchData() method.

Now let’s check whether the test cases are passing or not by running this command in your terminal.

flutter test test/api_provider_test.dart

Here api_provider_test.dart is your class name which you created for testing if your test cases pass the test you will get this response.

So this was all about unit testing in Flutter. Stay tuned for more articles related to other testing types.

Thanks for reading this article.

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

Connect with me on GitHub repositories.


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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

GraphQL and Flutter

0

If you are here that means you are seeking some information or knowledge or implementation technique of GraphQL, before going over the implementation of it with flutter you need to know what is it and why we need to implement it because without having a basic knowledge it might be a waste of time. So let’s take a look

What is GraphQL: It is a query language that allows us to create queries that will be executing on the server… Not Getting this bookish definition ??

Okay, Let me explain suppose if you are taking an exam and a few key points of any topic have been asked would you write whole info of that topic or specific points? Of course, key points because explaining it all would not be worthy, same in the GraphQL when you make API calls for the server you get no. of data fields but what if you need only two or three data fields from a huge collection? obviously you can use required data fields and all data fields which remained unused will not harm your app but in large scale projects, it reduces apps responsiveness so with the use of GraphQL we make queries for the specific data and we get exact data we required. it also helps especially when your internet connection is slow and then you need not fetch whole data because in the query you only request for specific data or only required data.

This was a small description about GraphQL and let us see

Here you can easily see that by using GraphQL server data is being fetched but in the query, only the name of the users has been asked and after pressing the top button, on the right side of the screen you can see the response that we got.

Now you would be thinking that it’s quite easy to make queries but how would a user get to know what kind of data the API is having. You need not be worry… GraphQL server also provides a schema of the API so you easily understand that

In this image of Documentation Explorer, there are two fields one is Query and the other is Mutation and by clicking on it you can find the required data for making query or mutation requests. This is my GraphQL API link you can try it.

So this was the introduction part now let’s implement it on fluter

Flutter Starts from here

First of all, you need to import a package of GraphQL in your pubspec.yaml

graphql_flutter:

You can find the latest version here and import

import ‘package:graphql_flutter/graphql_flutter.dart’;

GraphQL basically does two things

  1. Query: Query is used to fetching the required data.

2. Mutation: Mutation is used to update and insert data like for post/delete/put requests.

Then the first thing which comes to work with GraphQL is Client, and to use the client we first need to use link and cache here we are using httpLink as a link and OptimisticCache as a cache, We are also using ValueNotifier which is used to notify their listener when any value is changed.

Then we wrap our whole page with GraphQLprovider and after that, we will be able to make requests to the GraphQL server without specifying the endpoint and header and now we need to pass the query and then GraphQL provider will take care of it, it means it will perform actions for us.

In the query, there are two fields,

  1. options: Options are used to send the query you want to send.
  2. builder: builder is the same builder of flutter which is used to manage the states

In options, we use QueryOptions and use the documentNode function to pass the query which we have made and pass this through gql() because it parses GraphQL query strings into the standard GraphQL AST.

And this is the query that is being used to fetch the list of the data for this you can also use for testing in this GraphQL server. (you can see in the above picture)

query{
artworkAttributionClasses
{
name
}
}

Now in the builder function, we will fetch the data from the server and show in the screen,

For the full source code, you can click here

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

and for more knowledge about GrpahQL, please visit

graphql_flutter | Flutter Package
A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package.pub.dev

It was a small description about GraphQL.

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.

Related: Working with REST APIs

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Explore Precache Images In Flutter

0

Commonly it occurs (particularly in Flutter Web) that your pictures from local assets take a great lot of effort to load and deliver on your screen!

This isn’t useful from the user’s point of view particularly if the picture is the background picture of your screen. On the off chance that the picture is any part in your screen, we can in any case show shimmer, loader, or something so the user becomes acquainted with that picture is loading.

In this blog, we will explore the Precache Images In Flutter. We will execute a demo program of the Precache Images and show you how to load your image assets faster in your flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents ::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to use Precache Images in a flutter. It shows how Precache Images will work in your flutter applications. It shows when the user uses the precacheImage function, the image load faster from the assets folder. It will be shown on your device.

Demo Module :


Implementation:

Step 1: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

Step 2: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

precacheImage takes ImageProvider and context as required arguments and returns Future<void>

Future<void> precacheImage(
ImageProvider<Object> provider,
BuildContext context,
{Size? size,
ImageErrorListener? onError}
)

This strategy prefetches the image into the image cache and afterward at whatever point the image is utilized, it will be stacked a lot quicker. Nonetheless, ImageCache doesn’t permit to hold extremely huge pictures.

As the context is required in this, so we can add precacheImage() in any function from where context is accessible. We can place something similar in the didChangeDependencies() technique in our demo model.

First, we will create a two image variable was image1 and image2.

late Image image1;
late Image image2;

We add void initState() method. In this method, we will add variable image1 and image 2 is equal to add images from your assets folders.

@override
void initState() {
super.initState();
image1 = Image.asset("assets/flutter.jpeg");
image2 = Image.asset("assets/glass.png");

}

Since we need to preload our pictures when our widget is initialized, we can put our precacheImage code in the didChangeDependencies technique, which is called after initState, and at whatever point the dependencies change from there on, as follows:

@override
void didChangeDependencies() {
precacheImage(image1.image, context);
precacheImage(image2.image, context);
super.didChangeDependencies();
}

Now that all images have been preloaded, we can use them in our build method.

In the body, we will add a Center widget. In this widget, we will add a Column widget with the mainAxisAligment as the center. Also, add variables you were created for images.

Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
image1,
SizedBox(height: 50,),
image2
],
),
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Code File:

import 'package:flutter/material.dart';
import 'package:precache_image_example/splash.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

late Image image1;
late Image image2;


@override
void initState() {
super.initState();
image1 = Image.asset("assets/flutter.jpeg");
image2 = Image.asset("assets/glass.png");

}

@override
void didChangeDependencies() {
precacheImage(image1.image, context);
precacheImage(image2.image, context);
super.didChangeDependencies();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white24,
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text("Flutter Precache Images Demo"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
image1,
SizedBox(height: 50,),
image2
],
),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Precache Images in a flutter; you can modify this code according to your choice. This was a small introduction to Precache Images On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Precache Images in your flutter projects. We will show you what the Introduction is?. Make a demo program for working Precache Images. It shows when the user uses the precacheImage function, the image load faster from the assets folder in your flutter application. So please try it.

❤ ❤ 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.


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.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a 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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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


Related: Explore Layout Inspector In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Can Stateful Builder Step into the shoes of Stateful Widget?

0

The answer is: Ahh A big Noo….

To understand this let’s first understand what Stateful Builder is?

StatefulBuilder is a widget having a mutable state (whose state can be change) what makes it’s special is its only rebuild the particular widget which is wrapped under the Stateful Builder. Thankfully no again and again rebuilding of the whole widget.No matter the widget which is wrapped under the Stateful Builder is in Stateless or stateful Widget.

Now question arising is we know Stateless Widget it can’t rebuild until it gets a new instance. ( SetState is not working)

what happens is Stateful builder has the power of StateSetter function passed to the builder is used to call a rebuild itself instead of a typical state of the whole Widget.

StatefulBuilder(
builder: (BuildContext context, StateSetter setState) => Checkbox(
value: isChecked,
onChanged: (value) {
setState(() {
isChecked = value;
});
},
),
),

KEEP IN MIND

Any variables that represent state should be kept outside the build function means You have to declare the variable outside the build method for the magic happens.

As I mentioned above it only rebuild a particular widget. It only gives a new instance(State) to that particular widget. so you have wrapped all widget(view) you want to see the change in StatefulBuilder.

In order to understand Why can’t Stateful Builder replace a Stateful widget. Lets first understand what makes is different between Stateless and Stateful Widget.

Have you noticed in stateless override build method and on the other hand in Stateful widget first override createState and then override build method? What happens under the hood is when stateless widget gets an instance its build function is invoked. and in stateful widget first, create state giving instance to build function. get it?? That’s how our favourite setState is working. After running setState ,createState giving a new instance to build method and widget rebuilds.

Now we are in pretty much good condition to understand Why can’t Stateful Builder replace Stateful widget.

If it’s rebuilding the particular part of the widget tree. Why we can’t use instead of Stateful Widget?

If you store any state in instance variables in the stateless widget it may be lost at any time as the constructor for the stateless widget may be called repeatedly, just like the build method. Only the associated instance State of a Stateful widget is preserved by Flutter.

StatefulWidget is retained it state even across rebuilds, That’s why you see sometimes misbehaviour of TextEditingController in Stateless Widget

Or if you on sturboness of using StatefulBuilder with Stateless Widget then you have to save state by Global keys.

Link for repository

flutter-devs/StatefulBuilderDemo
stateful builder This project is a starting point for a Flutter application. A few resources to get you started if this…github.com

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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Flutter over other cross-platforms

0

So, in this era of growing automation, where the most used hand
handled device a.k.a smartphone is just not a mere device used for
calling anymore, the “Smart” prefix is used because of its highly
advanced capabilities making one’s life easier by providing day-to-day
activities in one place.

According to statista.com, the number of smartphone users worldwide is approx. 3.5 Billion as of 2020 and is forecasted to grow to 3.8 Billion by 2021. Now you can imagine the widespread use of smartphones and
how it is only meant to increase day by day. This enormous smartphone population is majorly dominated by two operating systems in the market, namely Android and iOS, and Android proving to be more dominating out of
both in the market. The duo accounting for 99% of the active
smartphones in the world wherein 2020 Android and iOS held a
market share of 74.3% and 24.76% respectively.

Where does Flutter come in between all this?

Okay, now imagine two different operating systems leading the
smartphone industry having different architecture, a different way of
working, a different way of building. From a developers point of view,
earlier there’s suppose be two different sets of developers, with different
programming knowledge which develops for either one of the OS. The
native apps are created specifically to be run on the target platform with
the support of all the native technologies and other hardware
components such as camera and calendar but they have some cons. With
the introduction of cross-platform app development the cons of the
native app development could be removed. In this, after writing the
application’s code, it can be deployed on different devices and platforms
without worrying about incompatibility issues with the advantages like:

  • Affordable and time saver
  • Easy and fast development
  • Wider audience reach

Various cross-platform app development frameworks are:
Appcelerator, PhoneGap, Kony, Xamarin, Sencha Ext Js, MonoCross,
AdobeBuild, React Native, Flutter.

What is Flutter?

Flutter is a mobile SDK for building high
apps for iOS and Android, from a single codebase

But wait, whenever one speaks about Flutter the one question that comes across the mind of someone not so familiar with it is, “Are you sure?

Bcoz that’s not even public”, the questions about its presence, about its consideration and if that it is then they are worth a thought because Flutter is like a newborn baby into the cross-platform app development framework but maintained by Google; a product of Google with some promising capabilities promoted with a tagline that Google uses to define it, “Build native apps in record time”.

Why use Flutter?

Before jumping onto the points stating out the features and advantages
of the Flutter, let’s talk about the previously existing methodology like

  • Native platform based SDKs

Like, Apple iOS SDK and Google AndroidSDKwhich using two different languages Objective-C/Swift and Java/Kotlin, respectively. Both SDKs are platform-dependent and have their own programming languages, so a developer either should know both the languages and even then they have to code individually or should miss out on the opportunity and just work for either one of the platforms.

On the other hand, Flutter being cross-platform framework deals with the concept of the individuality and helps writing a single code in a language called Dart that can be used to create an app for both the operating system thus saving the time of developers and not to miss the opportunity by being dedicated to a single platform.

  • WebViews
     Then came the cross-platform frameworks to deal with the cons of native frameworks but those cross-platform frameworks such as PhoneGap, Ionic, etc were merely based on Javascript and WebView.
    App using WebViews creates HTML and then displays it in a WebView on the platform and using the JavaScript bridge it is difficult for languages to talk directly to native code.
  • Reactive Views
     So to deal with the drawbacks of WebViews Reactive web frameworks like ReactJS came in use which provides the simplified WebView through the use of reactive programming.

This doesn’t use the concept of WebViews and instead uses a JavaScript bridge to access the native widgets which can cause performance issues as widgets are typically accessed frequently. On the other hand, Flutter also provides reactive style views but makes the use of complied programming language namely Dart to avoid the performance issues caused by the JavaScript bridge.

Flutter vs Other Hybrid Technologies

Flutter vs Xamarin:

  • The tussle of programming languages:

Xamarin uses C# which is one of the popular programming languages among the developers and if you’re familiar with it then you can straightaway start using Xamarin. But Flutter uses Dart language though relatively new but if you’re familiar with the concepts of OOPs languages such as Java, C++ then learning Dart isn’t much of a trouble. In fact, dart has many capabilities like:

  1. It can be trans-complied to javascript using the dart2js compiler.
  2. Dart also supports both AOT and JIT compilation which makes the processing faster.
  3. Even though C# is one of the top popular languages on GitHub but Dart
  • Community Support

Xamarin has been in the field for long now and thus have a larger community, which comprises of experienced and willing to share knowledge developers. On Xamarin forums, committed developers share their code and experience, helping each other out. The platform is also supported by Microsoft which keeps updating its documentation from time to time. On the other side, though Flutter is the new age framework introduced its stable version in 2018, it had a limited community at its early stages but with time its community has upsurged abruptly, the Twitter community is approx 80k+ while that of Xamarin is 70k+ followers, the Reddit community is approx 30k+ followers and 88k+ stars on Github, the community has challenged their rivals in less time.

Flutter vs React Native:

  • The tussle of programming languages:

The comparison among the programming languages is inevitable when comparing two different frameworks to marks one’s processing. React Native supports various languages like JavaScript (dynamically typed), Typescript and JS with flow. While Flutter supports Dart which is a newly introduced language based on the concept of OOPs so it won’t be a hassle to work across it.

  • Community Support

React Native has been in the field since 2015 and Flutter released the first stable version in 2018 yet Flutter has surpassed React on Github with Flutter at 88k+ stars and React at 85k+ stars which itself tells you about the take of the developers regarding the both. React which is considered on the best Cross-Platforms is facing challenges from Flutter.

What do the stats say?

This is the data from the last 12months and the curiosity about flutter has been surging in the developers’ minds all around the world.

Advantages of Flutter:

Fast development

  • Flutter uses a Hot Reload feature which makes the app
    development more dynamic and faster.
  • Suppose you have to make some changes like add
    features, fix bugs, to the code and want those changes to
    be implemented instantly, Hot Reload is what makes it
    happen in flutter where the changes are added in
    milliseconds.
  • This Hot Reload feature comes way handy in the developer-
    designer/tester relationship, where the latter can work together with the developer on UI, making changes.

Beautiful, vivid UIs

Flutter has a rich set of Material design and Cupertino
widgets which help to build customized, beautiful designs
without the limitations of OEM widgets.

Native performance

Flutter widgets incorporate all the indifferences of both the
native platforms, iOS, and Android such as scrolling,
navigation, icons, and fonts which provide native performances
on both.

Productivity

Flutter provides high productivity by developing apps for both
iOS and Android just by using a single codebase. The
developers just have to write the code once and that single
code will be able to build apps for both platforms.

Flutter for all

Flutter, started as the cross-platform development tool specifically focusing on the apps on the smartphone but that wasn’t it’s limit, Flutter for web was introduced with Flutter v1.12 as a beta version, which is basically web apps using Flutter. Also, Flutter is like the first-class citizen of Fuschia OS. Now, you can also build apps for MacOS, flutter enabled support for MacOS in the dev channel as of 1.13.

Various Programming Standards

  • Concurrent programming
    Flutter makes abundant use of asynchronous functions such as Futures to do task parallelly. For example, To report when an image is loaded, futures are used on the basis of whether a future has been completed or not.
  • Composition
    Since everything in Flutter is a widget and when I say everything it means everything. Flutter makes efficient use of composition in its widgets creation, its composes objects with a limited behavioral span to make a complex widget. For example,
  • Generic Programming
    “types-to-be-specified-later” seems less hectic in programming, Flutter follows the same paradigm throughout its structure. For example, the state class takes a parameterized widget type.
  • Reactive Programming
    In Flutter, the widget and the element trees are reactive in nature. Reactive in the sense that any changes in the state are immediately propagated down the widget tree using the build method and are also propagated back up the widget tree using the event handlers.

With the increase in curiosity in the developer community, an increase in popularity in the GitHub, the fact it’s being backed by the upsurging and established tech giant Google and looking at its various advantages you can definitely look it up for building a cross-platform app. The only major competitor you might have in mind might be ReactNative but taking in the time/popularity ratio into consideration, I think Flutter should be your go.


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.

Related: Dialog Using GetX in Flutter

Related: Switch Theme Using Bloc With Cubit In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

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. 🌸

Related: SMS Using Twilio In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

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. 🌸

Related: Dialog Using GetX in Flutter

Related: Switch Theme Using Bloc With Cubit In Flutter

Related: Bottom Navigation Bar using Provider | Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

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. 🌸

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

www.flutterdevs.com

Complete Guide to Firebase Firestore in Flutter 2026

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. 🌸

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

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. 🌸

Related: Explore SOLID Principles In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.