Google search engine
Home Blog Page 32

Know Your Widgets: Scaffold in Flutter

0

If you’re here then you must’ve just started to work in Flutter and might have come across the Scaffold ‘thing’ almost everytime, like EVERYTIME and I am pretty sure you must’ve come across various ambiguous questions.

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Drawer Module"),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
new UserAccountsDrawerHeader(
accountName: Text("xyz"),
accountEmail: Text("xyz@gmail.com"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.white,
child: Text("xyz"),
),
otherAccountsPictures: <Widget>[
new CircleAvatar(
backgroundColor: Colors.white,
child: Text("A"),
)

],
),

This is just a example of a module showing the root and basic requirement of scaffold in building an app in Flutter.

So, you must be curious to know about the Scaffold widget and it’s properties in flutter. Don’t worry we got your back, this blog will give you the basic knowledge about Scaffold and how to use it while creating your basic module.

Let’s go…..

What is Scaffold?

A Scaffold Widget provides a framework which implements the basic material design visual layout structure of the flutter app. It provides APIs for showing drawers, snack bars and bottom sheets. Have a look at its constructor and the properties it has. We are going to overview it’s parameters one by one.

//Constructor of Scaffold
const Scaffold({
Key key,
this.appBar,
this.body,
this.floatingActionButton,
this.floatingActionButtonLocation,
this.floatingActionButtonAnimator,
this.persistentFooterButtons,
this.drawer,
this.endDrawer,
this.bottomNavigationBar,
this.bottomSheet,
this.backgroundColor,
this.resizeToAvoidBottomPadding = true,
this.primary = true,
})

Scaffold contains various functionality from giving an appbar, a floating button, a drawer, background color, bottom navigation bar, footer buttons,body. Now, let’s explore them individually:

  • appBar
    An appBar is to display at the top of the scaffold it’s one of the primary content of Scaffold without which a scaffold widget is incomplete. It defines what has to be displayed at the top of the screen. appBar uses the AppBar widget properties through Scaffold.appBar. This AppBar widget itself has various properties like title, elevation,brightness etc to name a few.
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Scaffold'),
),

Here, the title property of AppBar uses Text widget to display the text on the app bar.

Fig 1: Display an AppBar
  • body
    body is the other primary and minimum required property of the scaffold which signifies the area below the app bar and behind the floatingActionButton and drawer. Any widget in the body of scaffold is positioned at the top-left corner by default.
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Scaffold'),
),
body: Center(
child: Text("This is Homepage",
style: TextStyle(
color: Colors.black,
fontSize: 40.0,
fontStyle: FontStyle.italic,
),
),
),

Here, the body property of the Scaffold is used to display a text “This is HomePage”. The Centre widget is used to align the text at the centre of the body and a Text widget is used to give the text along with it’s style property which gives the text a color, fontsize and fontstyle. Don’t worry this blog isn’t about the Centre or Text or TextStyle widgets, they will be covered later.

Fig 2: Text displayed inside the body
  • floatingActionButton
    A floatingActionButton is a button displayed floating above body in the bottom right corner. It is a circular icon button that hovers over content to promote a primary action in the application. floatingActionButton uses the FloatingActionButton widget properties through Scaffold.floatingActionButton.
  @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Scaffold'),
),
body: Center(
child: Text(
"This is Homepage",
style: TextStyle(
color: Colors.black,
fontSize: 40.0,
fontStyle: FontStyle.italic,
),
),
),
floatingActionButton: FloatingActionButton(
elevation: 10.0,
child: Icon(Icons.add),
onPressed: (){
print('I am Floating button');
}
),
);
}

Here, the elevation property of the FloatingActionButton is used which gives shadow to the button and Icon widget is used to give an icon to the button. The onPressed property provides a callback that is called when the button is tapped, when you tap the button “ I am a Floating Button” gets printed on the console window refer Fig 4 below .

Fig 3: A floatingActionButton with an icon
Fig 4: onPressed callback is called when tapped
  • floatingActionButtonLocation
    By default, the floatingActionButton is positioned at the bottom right corner of the screen so as the name says floatingActionButtonLocation defines the position of the floatingActionButton using the predefined contants like,

centerDocked

floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,

centerFloat

floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,

endDocked

floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,

endFloat

floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
Fig 5: floatingActionButtonLocation constants
  • drawer
    A drawer is a panel displayed to the side of the body, often hidden on mobile devices. One usually has to swipe left to right or right to left to access the drawer. 
    It uses the Drawer widget properties which is a material design panel that slides in horizontally from the edge of a Scaffold to show navigation links in an application and this widget is used in scaffold using Scaffold.drawer property.
drawer: Drawer(
elevation: 16.0,
child: Column(
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text("xyz"),
accountEmail: Text("xyz@gmail.com"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.white,
child: Text("xyz"),
),
otherAccountsPictures: <Widget>[
CircleAvatar(
backgroundColor: Colors.white,
child: Text("abc"),
)
],
),
ListTile(
title: new Text("All Inboxes"),
leading: new Icon(Icons.mail),
),
Divider(
height: 0.1,
),
ListTile(
title: new Text("Primary"),
leading: new Icon(Icons.inbox),
),
ListTile(
title: new Text("Social"),
leading: new Icon(Icons.people),
),
ListTile(
title: new Text("Promotions"),
leading: new Icon(Icons.local_offer),
)
],
),
),

Here, the drawer property of scaffold is used to create a drawer. We used various other widget inside this to make a little attractive drawer but don’t worry about all the other widgets, as we’ll be covering in the series.

Fig 6: drawer
  • persistentFooterButtons
    persistentFooterButtons is a list of buttons that are displayed at the bottom of the scaffold. These buttons are persistently visible, even if the body of the scaffold scrolls. They will be wrapped in a ButtonBar and are rendered above the bottomNavigationBar but below the body.
persistentFooterButtons: <Widget>[
RaisedButton(
elevation: 10.0,
onPressed: () {},
color: Colors.green,
child: Icon(
Icons.add,
color: Colors.white,
),
),
RaisedButton(
elevation: 10.0,
onPressed: () {},
color: Colors.blueGrey,
child: Icon(
Icons.clear,
color: Colors.white,
),
),
],

Here, persistentFooterButtons take a list of widgets or buttons. In this we have used the RaisedButton if you want you can use the FlatButton instead.

Fig 7: persistentFooterButtons
  • bottomNavigationBar
    bottomNavigationBar is used to display a navigation bar at the bottom of the scaffold. It is rendered below the persistentFooterButtons and the body.
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0,
fixedColor: Colors.teal,
items: [
BottomNavigationBarItem(
title: Text("Home"),
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
title: Text("Search"),
icon: Icon(Icons.search),
),
BottomNavigationBarItem(
title: Text("Add"),
icon: Icon(Icons.add_box),
),
],
onTap: (int index){
setState(() {
_currentIndex = index;
});
},
),
Fig 8: bottomNavigationBar
  • endDrawer
    A enddrawer is like a drawer property but in enddrawer by default the drawer is display at the right side of the screen.
  • primary
    Whether the scaffold is being displayed at the top of the screen. If true then the height of the appBar will be extended by the height of the screen’s status bar, i.e. the top padding for. The default value of this property is true.
Fig 9: Shows primary property of scaffold
  • backgroundColor
    This property sets the background color of the scaffold.
backgroundColor: Colors.white,
  • resizeToAvoidBottomInset
    If this property is true the body and the scaffold’s floating widgets should size themselves to avoid the onscreen keyboard whose height is defined by the bottom property.
    For example, if there is an onscreen keyboard displayed above the scaffold, the body can be resized to avoid overlapping the keyboard, which prevents widgets inside the body from being obscured by the keyboard. Defaults to true.

So, this was all about the various properties of the Scaffold which just gives you an overview of Scaffold. The purpose was to get your familiar with different properties and their usage for more detailed on the Scaffold widget refer to the flutter documentation here.

And for any other documentation related query on flutter click here.
Also check the github repo for Scaffold.


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


Machine Learning in Flutter

0

So, I know Machine Leaning is there in open and it has been there for quite long. It goes way back in the previous century when it was first coined and brought into existence, now you find it everywhere in daily life so important that your life is probably surrounded by it and you may even not know, consider your smartphones they are called “smart” for a particular reason and in today’s time they are “smartest” while getting even more n more from day to day, because they are learning about you from you itself the more you’re using it the more your smartphone gets to know you and all of that is just the machine with lines of code evolving with time like humans. It’s not just limited to smartphones, it’s extensive in technology.
 But talking about smartphones consisting of apps which makes your life easier on a daily basis, using Machine Learning is a smarter way to build apps and with Flutter building cross-platform apps have been fun for a while and what if you are able to build an intelligent app with fun using Flutter? Don’t worry we got you sorted and we got it from basics giving you an overview step-by-step which will help you build Flutter apps using Machine Learning.

Machine Learning Overview:

Field of study that gives computers the capability to learn without being explicitly programmed.

In a laymen language, one must define Machine Learning as the scientific study of statistical models and algorithms that a computer uses to effectively perform specific tasks without having to provide explicit instructions. It is an application of Artificial Intelligence that enables a system to learn and improvise through experience, where a system can collect the data and learn from it.

What does learning mean to a Computer?

A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P if its performance at tasks in T, as measured by P, improves with experience E.

For example: Take an example of playing chess 
Here, 
E = the experience gained from playing chess 
T = the task of playing chess
P = probability of winning the next game

Examples of implementation of machine learning in real life:

You know the general practice to understand something or making someone understand a thing is always try exploring its real-time use in your life. So, following that practice lets us consider some real-life scenarios where one come across Machine Learning in day to day basis.

1. Google photos, we guess everyone is aware of this app on your phone made and maintained by Google, one special and an excellent feature that it practice is the use of machine learnings Face Recognition algorithm in its app. It helps to recognize the people in your photos based on their facial identification. Never encountered it? Head over to the Photos app and experience it yourself.

2. Google Lens, released in the second half of 2017, this Google app helps image recognition in real time, just hover your camera to an image or ask google assistant to scan an image using this app to get insightful information extracted from the image. Be it taking an action in the text like saving the contact, fetching the e-mail ID or finding a dress you like in the image over the web or exploring the places nearby or identify plants and animals. This app makes you explore smartly giving you the futuristic feel and all of this is possible because of one thing i.e. Machine Learning.

3. Shopping Online, This is another most come practiced implementation of Machine Learning. Did you ever notice that when you’re trying to buy a product from an online platform frequently but you didn’t buy it somehow be it because of any reason then your social media like Facebook, your webpages or even the shopping store start recommending you that particular product? This is all possible not because of some human being sitting on a desk and pushing you these adverts NO, in fact, this is Machine Learning algorithms that does it.

4. Medical Enhancements, Yes!, Machine Learning plays a crucial role in the medical field too. Nowadays, the detection of various disease is done just by looking at the slide(cell image) and all of this is performed by machines using the model’s scientists have developed, for something which humans would take a significant amount of time.

And frankly speaking this list of examples is quite long, just imagine anything that learns from its past experience and grows in time.

Firebase and Machine Learning:

So, that was just an overview of Machine Learning giving you a brief about What is Machine Learning? and Where do you come across it in a day to day activity? Well, don’t worry we didn’t lose the track of our objective here which by the way is to get familiar with Machine Learning in Flutter. Heading forward with our objective the next topic to explore is about Firebase. We will start with why we have to explore Firebase here.

Firebase is Google’s mobile and web app development platform that provides developers with a plethora of tools and services to help them develop high-quality apps usually by providing a backend to the app. Most developers use it to create a database to their apps as it helps build apps faster without having to take care of the managing infrastructure.
 We will be using firebase because of Firebase ML kit which is a mobile SDK that brings Google’s machine learning expertise to Android and iOS apps in a powerful yet easy-to-use package. Whether you’re new or experienced in machine learning, you can implement the functionality you need in just a few lines of code. There’s no need to have deep knowledge of neural networks or model optimization to get started. On the other hand, if you are an experienced ML developer, ML Kit provides convenient APIs that help you use your custom TensorFlow Lite models in your mobile apps.

Main highlights of Firebase ML kit:

1. Production ready:
 Firebase ML Kit comes with a set of ready to use APIs such as Image recognition, Text recognition, face detection, land identification, barcode scanning, image labeling, and language identification. You just have to use the libraries and it feeds you with the information you need.

2. Importing Custom Model:
 Suppose you have your own models of ML that you have made in Tensor Flow, don’t worry Firebase got you all covered making it easy for you by letting you import your Tensor flow lite models, just upload your models in firebase and firebase will take care of hosting and serving it to you. Firebase acts as the API layer to your custom model.

3. Cloud or On-device:
 Whether you want to use it for cloud services or on-device, firebase ML kit works smoothly, securely and efficiently everywhere. Their APIs works both on the cloud and as well as on-device. On-device it even works when there are network issues while on-cloud it is powered by Google’s cloud platform machine learning technology.

Work Methodology:

So, you must be wondering how does all of this even works and if that is the case trust us, we were in the same position as you are right now until the moment we started to dig and it came out all as easy as pie, ML kit implements Google’s Machine Learning Technology, such as Google Cloud Vision API, TensorFlow lite and Android Neural Network API in a single SDK. Now just imagine the power of all these technologies under one hood; whether you want to hold the power of cloud processing or be it the real-time potential of mobile-optimized models or even your custom models, all of it is just handled in few lines of code.

Implementation:

The path of implementation includes just three steps, yes! just three:

1. SDK integration:
 Integrate the SDK using gradle.

2. Prepare input data:
 Let us explain it with an example, if you’re using a vision feature, capture an image from the camera and generate the necessary metadata such as image rotation, or prompt the user to select a photo from their gallery.

3. Apply the ML model to your data:
 Using the ML model to your data, you can generate a wide spectrum of insights such as the emotional state of detected faces or the objects and concepts that were recognized in the image, depending on the feature you used. Then you can implement these insights to power features in your app like photo embellishment, automatic metadata generation.

Various ready-to-use APIs:

  1. Text Recognition:
     By using ML Kit’s text recognition API you can identify text in any Latin-based languages which in general sense means almost all languages. It can maneuver the tedious data by itself and by using the cloud-based API you can even extract text from the picture of documents and also apps can track real-time objects.

2. Face Detection:
 By using ML Kit’s face detection API you can detect faces from an image and identify their key facial features like locate eyes, nose, ears, cheeks, mouth and even get contours of the detected faces. The information collected through this API can help embellish your selfies like when you want to add beauty to your face in real-time and help capture portraits in portrait mode. It helps perform face detection in real-time so you can use it to generate emojis or add filters in a video call or snap.

3. Barcode scanning:
 By using ML Kit’s barcode scanning API you can scan the barcodes to get the encoded data. Barcodes are a convenient way to pass information of the real world to your app. It can encode structured data such as Wi-Fi credentials or contact information.

4. Image Labeling:
 By using ML kit’s image labeling API you can recognize various entities in an image without having to provide any additional metadata from your side either using on-device or cloud-based API. Basically, image labeling gives you an insight about the content in your image. When you use this API you get the list of entities that were recognized such as people, places, activities and more. Each label comes with a score that mentions the confidence level of the ML model on its observation.

5. Landmark Recognition:
 By using landmark recognition API you can recognize the popular landmarks in the image provided to the API by you. After passing the image to it, you get the landmarks that were recognized in the image, along with the coordinates and the place where the landmark is located.

6. Language Identification:
 By using language identification API you can determine the language from the given text. This is helpful when working with user-provided text where the information about the language isn’t provided.

Integrating Machine Learning Kit in Flutter:

Phewww! That was a lot of background knowledge but NO that was not to just to spam it with words, in fact, all of that was to give you an overview of Machine Learning and Firebase’s ML Kit and if you were already aware of them then you know how crucial it was to know before moving any further.
 But finally, we’re at the part where we integrate Firebase’s ML Kit with Flutter and its just a piece of cake now onwards.

1. Installing plugins:
 
The basic requirement is to install a Flutter’s ML vision plugin which has been built by the flutter dev team itself and to explore more from them click here. You can use a couple of more plugins depending on your requirement like if you gonna use the Image identification then use image picker plugin which makes you choose either from clicking an image using a camera or get an image from the gallery.

2. Setup the firebase project:
 
If you are already know how to setup a firebase project then you are good to go for this step and if you aren’t aware of it then below is a video which will help you setup a firebase project using Firebase’s Cloud Firestore over Firebase Real-Time database.

To know about Cloud Firestore, watch

Now, you’re done and good to go with the fundamental requirements and knowledge required to use Machine Learning in Flutter. You can use the various APIs that are available with Firebase ML Kit to get your work done. On this blog, we won’t be discussing the codelab for Machine Learning but we’ll be bringing a codelab in our next blog so stay tuned. This blog was to give you an overview of Machine Learning, Firebase ML Kit and Flutter integration.

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


Know Your Widgets: Row and Column in Flutter

0

So, the next widget in our series is not just a single widget, in fact, we would be covering two different widgets in this blog, namely Row and Column. The reason behind integrating two widgets together is the fact these two widgets have similar properties which will help you understand them efficiently.

So, by now you must be familiar with what flutter is and what widgets are. We know everything in Flutter is a widget that means everything you see on a screen is a widget in a Flutter and flutter have lots of widgets, widgets for almost every functionality you wanna put it, if you head over to flutter widgets at flutter.dev you will find a whole list of widgets.

Similarly, Row and Column are also widgets in Flutter and mostly every layout can be broken down in row and column, it’s that important. So let’s explore them individually …

Row

Let’s suppose you want to display a number of widgets in a horizontal manner on the screen, like a Text and an Image and we’re pretty sure you will find this minute requirement everywhere in a layout. That’s where Row widget comes in use, which displays the widgets in a horizontal manner.

A row is a multi-child layout widget which takes in a list of widgets as its children. A row displays the widgets within the visible view i.e. it doesn’t scroll. Use ListView widget to create a scrollable list of widgets, we’ll discuss this widget further in the series.
 For now, consider this code snippet which contains Row widgets containing Text widget wrapped in Flexible widget and a FlutterLogo widget.

This code will display a text and flutter logo in a row as shown in the pic below.

Note: Flexible widget is used to wrap the text because if the content of the row is wider than the row itself, then the row is said to have overflowed. When a row overflows, the row does not have any remaining space to share between its children and the row reports this by drawing a yellow and black striped warning box on the edge that is overflowing. Refer to the code snippet and the output below for the overview of the issue and importance of Flexible or Expanded.
 We will talk about the Flexible and Expanded widgets in other blogs, for now just understand its use.

Column

Now, we know that to lay the widgets in a horizontal manner we can use a Row widget but what to do when you have to lay the widgets in a vertical manner, that’s where Column widget comes in play.

Column widget alike row is a multi-child layout widget which takes in a list of widgets as its children.
 Consider this code snippet which contains a Column widgets containing two flutter logos and a text widget.

This code will display a Text between two Flutter logos as shown in the pic below,

Note: Here we didn’t have to wrap the children inside Column with either Flexible or Expanded widgets because for now the content of the children fit the column view perfectly but you might come across a situation where your content of the Column exceeds the amount of space available, in that case the Column overflows resulting in your content getting clipped and a warning is display in the form of yellow and black striped bar indicated at the overflowing edge with a message telling by how much your content has overflowed. Refer to the code snippet and the output below to get an overview of the overflow situation. One can use the Flexible or Expanded widgets to restrict the content to the visible view of the screen but if you want a scrollable vertical list of widgets then use a ListView instead of Column.

Properties of Row and Column

By now you must have a vivid overview of,

  1. What are Row and Column widgets?
  2. How to use Row and Column.
  3. When to use and when not to use?
  4. Basic problems faced with Row and Column
  5. And how to deal with it.

Now moving forward let’s look for their properties and see what functionality either of the widgets offers though Row and Column have the same set of properties but works in a slightly different manner. Let’s see those properties.

Row properties:

Here is the constructor of the row with some default values,

Column properties:

Here is the constructor of the column with default values,

It’s clear from the constructors that they have similar properties but their usage differs, so we’ll discuss each property by comparing their usage in both row and column.

mainAxisAlignment
Let’s first understand what mainAsix is, mainAxis is the longest side of row and column, for a row mainAxis is the horizontal side while for the column mainAxis is the Vertical side. 
This property positions children widgets along the main axis of the layout.

center
 
This positions the children as close to the middle of the main axis as possible.

end
 
This positions the children as close to the middle of the main axis as possible depending on the textDirection.

spaceAround
 
This distributes the free space evenly between the children and half of that free space is used before and after the first and last child respectively.

spaceBetween
 
This distributes the free space evenly between the children.

spaceEvenly
 This distributes the free space evenly between the children and before and after the first and last child respectively.

start
 This positions the children close to the start of the main axis depending on the textDirection.

mainAxisSize
 
This property directs how much space the children should occupy in the main axis. In the layout, after allocating spaces for the children there might be some free space. mainAxisSize tells whether to maximize or minimize the free space.

min
 
It minimizes the amount of free space along the main axis.

max
 
It maximizes the amount of free space along the main axis.

crossAxisAlignment
 
Let’s first understand what crossAxis is, crossAxis is the smallest side of row and column, for a row crossAxis is the vertical side while for the column crossAxis is the horizontal side. This property positions children widgets along the cross axis of the layout.

start
 
This positions the children start edge to the start side of the cross axis. For ex: if this is used in a column with the textDirection set to TextDirection.ltr, it aligns the left edge of the children to the left edge of the column.

end
This positions the children as close to the end of the cross axis.
For ex: if this is used in a column with the textDirection set to TextDirection.ltr, it aligns the right edge of the children to the right edge of the column.

center
This positions the children such that their center aligns to the middle of the cross axis. By default the value of crossAxisAlignment is center.

stretch
This lets the children to completely occupy to the cross axis.

baseline
This positions the children such that their baseline match.

textBaseline
It’s the horizontal line used for aligning the text.

textDirection
This property determines the order in which to lay the children horizontally.

rtl
It lays the children from right to left direction.

ltr
It lays the children from left to right direction.

verticalDirection
This property determines the order in which to lay the children vertically.

children
Both these widgets, Row and Column, takes a list of widgets as its children.

So, these were the properties that are included in Row and Column widget, the purpose was to give you an overview of Row and Column widget in the flutter, now it’s your time to explore them and get more familiar with the in-hand experience. remember, the basic rule that we are made familiar with right from childhood is If you don’t practice, you don’t learn. Implement these properties yourself and let us know if we made a mistake or left out something.

If you want to read more about row and column head over to the flutter docs of Row and Column.

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


Data Persistence with SQLite | Flutter

0

Whenever you need to store the data on the local then you need to use SQLite to persist the user data.

Why we use SQLite?

SQLite is a popular choice as embedded database software for local/client storage in application software such as web browsers.

How to use SQLite in a flutter?

Before using SQLite, you should know that

SQLite is not available in a flutter SDK like Android but we have a plugin sqflite that exactly performs all the operation on the database just like in Android and iOS.

Flutter plugin is the wrapper of the native code written in Kotlin or java for Android and swift or objective-c for iOS.
P.S : Plugin can also be created only with dart code

If you are new to SQLite, go through SQLite Tutorial site below

SQLite Tutorial – An Easy Way to Master SQLite Fast
This SQLite tutorial teaches you everything you need to know to start using SQLite effectively. You will learn SQLite…www.sqlitetutorial.net

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file .

  sqflite:
path_provider:

To work with SQLite databases, import the sqflite and path packages

  • The sqflite package provides classes and functions that allow you to interact with a SQLite database.
  • The path_provider package provides functions that allow you to correctly define the location to store the database on disk such as TemporaryDirectory and ApplicationDocumentsDirectory.

Step 2: Create a Model class

SQLite creates a table for the model class, the fields in the class correspond to columns in the table. Therefore, the classes tend to be small model classes that don’t contain any logic. Our Person class represents the model for the data in the database.

class Person {
int id;
String name;
String city;

Person({this.id, this.name, this.city});

}

If we want to insert into the database then we need to convert the Person into a Map

Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"city": city,
};

and if we want to retrieve from the database then we need to convert the Map into the Person

factory Person.fromMap(Map<String, dynamic> json) => new Person(
id: json["id"],
name: json["name"],
city: json["city"],
);

This is how our PODO class will look like

https://gist.github.com/ashishrawat2911/d74ea7944b53f193832793c1fe5f54a9#file-person-dart

Step 3: Create a database

We will make a separate class as database.dart to make the code more modular and add all the requirements meths for managing the database that can be accessed anywhere in the app.

Create a class DatabaseProvider

class PersonDatabaseProvider{
DatabaseProvider._();

static final PersonDatabaseProvider db = PersonDatabaseProvider._();
}

Step 4: Open the Database

Before you read and write data to the database, you need to open a connection to the database. This involves two steps:

  1. Define the path to the database file using the getDatabasesPath from the sqflite package combined with the pathfunction from the path package
  2. Open the database with the openDatabase function from sqflite
Directory directory = await getApplicationDocumentsDirectory();

String path = join(directory.path, "person.db");

final Future<Database> database = openDatabase(path);

Step 5: Create the table

you need to create a table to store information. 
For example, In our case, we create a table called Person that defines the data that can be stored. In this case, each Person contains an id, name, and city. Therefore, these will be represented as three columns in the Person table.

  1. The id is a Dart int, and will be stored as an INTEGER SQLite Datatype. It is also good practice to use an id as the primary key for the table to improve query and update times.
  2. The name is a Dart String, and will be stored as a TEXT SQLite Datatype
  3. The city is also a Dart String, and will be stored as an TEXT Datatype

To prevent from opening a connection to the database again and again we can use this:

https://gist.github.com/ashishrawat2911/a59ab9ece9649d1de3dc9527b870c99b#file-createdatabase-dart

Step 6: Managing the data

Now we are going to show you how you can perform an operation on the SQLite database.

Query:

https://gist.github.com/ashishrawat2911/333a6b650568b9b59468a2e70e33175b#file-query-dart

getAllPersons() will return all the person from the SQLite database if available.

Insert:

https://gist.github.com/ashishrawat2911/2ed7bcdf77d253d4940bcf0681afbc6d#file-insert-dart

Delete:

https://gist.github.com/ashishrawat2911/5969e225083a5c8ff995618fdab95a01#file-delete-dart

If you see we have two methods, one deletes the row with particular id and other deletes all data present in the table, you can change all the query according to your need.

Update:

https://gist.github.com/ashishrawat2911/f25acd6599b120bfa3e1d68a58b4430d#file-update-dart

If these small code snippets still confuse you we have the complete code of the database class:

https://gist.github.com/ashishrawat2911/16c4d20501f8bec519b914ee6e49480d#file-database-dart

Step 7: Using the data

In order to use the database we need to create the instance of the database and use the method present in the database class

DatabaseProvider.db

This will help us to perform an operation on the database.

like if we want to get the person in the database we will use the method that we have defined in our DatabaseProvider class

DatabaseProvider.db.getAllPersons()

and if I want to display it in the list then I’ll use FututeBuilder :

https://gist.github.com/ashishrawat2911/fdf814c9638976a57d440329a318257f#file-bodysql-dart


we have also linked a repo if you need to see the example of SQLite.

ashishrawat2911/flutter_sqlite
Contribute to ashishrawat2911/flutter_sqlite development by creating an account on GitHub.github.com

That it for SQLite in flutter.

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.

Connect with me on Linkedin and Github


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


Google Maps in Flutter

Google Maps, we all are quite aware of the fact of how crucial Maps are in our life, from locating a place to locating nearby shops, in our daily commute, taxi, food deliveries. The first thing to observe is how important maps are? and the second thing to observe is that most of the apps these days have maps in them, so Maps in App development are becoming a serious thing from day to day. Now when we are talking about development in Flutter, its a fact that maybe you come across a situation where you want to implement maps in Flutter and the first question after that thought comes is HOW TO IMPLEMENT IT? or WHERE TO START FROM?

In this article, we’ll answer your questions like, maps in Flutter, how to use maps in Flutter, implement google maps in Flutter and will help you from setting it up to creating a small module using Maps in Flutter.
 In this article, we’ll be using the Google Maps plugin for Flutter which has been developed by Flutter team themselves.

Where to start from?

Now, that you’re here, you’ll be curious about a particular question, from where you should I start? It’s probably the first thing that comes to our mind whenever we start with anything, isn’t? Don’t worry, we’ll guide you from prerequisite required to displaying the map on your screen and then moving on to what other things can you do using this plugin. So, Let’s start with setting up your project which will stand as the base on which your map will be displayed.

The setting up process includes two things, namely:

Adding the plugin

1. As you know, we’ll be using the Google Maps Plugin which you can find here. This is the official Google Maps plugin developed by the Flutter team.
 2. Add the plugin as the dependency in the pubspec.yaml file, as shown below.
 3. Now, get the packages using the flutter packages get command.

https://gist.github.com/Aditsyal/ffc8fca87002172fdbdaaed2648fa4e1#file-pubspec-yaml

Integrating Google Maps API key

The next step is the last step before you could start coding for the map in Flutter and undoubtedly the important one as this step involves integrating your Google Map API key into your project for both the platforms Android and as well as iOS.

For Android
Create the Google Maps API key from here
– Add the API key in the AndroidManifest.xml file(android/app/src/main/AndroidManifest.xml).

https://gist.github.com/Aditsyal/ad5491a60fc84918af0492b5a933d657#file-androidmanifest-xml

For iOS
Create the Google Maps API key from here
– Add the API key in the AppDelegate.m file(iOS/runner/AppDelegate.m).

https://gist.github.com/Aditsyal/e4e9054b84f691ebafd12f67dea1fea9#file-appdelegate-m

– Now, add a setting to app’s Info.plist file(iOS/runner/Info.plist).

https://gist.github.com/Aditsyal/eee7d791e44b7ac73b0facc9e7b608a3#file-info-plist

If you’ve done everything as said up till now then you’re all set up but there might be some issues regarding the API key setup which we’ll be answering towards the end of the article. Now, you can start using the GoogleMap widget in Flutter.

Using GoogleMap Widget

So, now that you’ve setup your project and we guess all went good, you can display the map using the GoogleMap widget in Flutter.

https://gist.github.com/Aditsyal/e5115389fd70f6d5628c25a25f88a1d0#file-googlemapwidget-dart

This snippet of code will help you display the map on your app, just with few lines of code and you get the basic map displayed on the screen, you can scroll it, zoom in, zoom out are the basic gestures by default. Look at the snapshot below to understand.

Points to understand from the above snippet:

initialCameraPosition: This gives the starting position of the map when it is opened for the first time. Here, we gave the Latitude and Longitude of Egypt, using the CameraPosition Widget which takes the LatLng in its target property. The Camera here describes the view of the user i.e what position in the map should the user be able to view.

GoogleMapController: It’s the controller for a single GoogleMap instance running on the host platform. This controller is like any other controller be it TextEditingController, this manages various functionalities like camera position, zoom, animation, etc.

onMapCreated: This method is called when the map is created and takes the GoogleMapController as its parameter.

GoogleMap constructor:

Now, that you’re able to display the basic map with least of its functionality we’ll move forward to see what all the functionality does this widget holds as clearly just knowing this won’t be sufficient enough. So, let’s start with getting to know the properties that the GoogleMap widget gives us, here is the constructor of the GoogleMap widget:

https://gist.github.com/Aditsyal/fa2e2d291c74114efc344e5121916afc#file-googlemapconstructor-dart

This constructor tells us the various parameters that the widget takes, so here we can see the list of functionality that this widget provides using the plugin. We already gave you a brief about the onMapCreated and the initialCameraPosition properties, so we’ll be skipping these and will give you a brief about the remaining others,

1. gestureRecognizers: This property tells us which gestures should be consumed by the map. It is possible for other gesture recognizers to be competing with the map on pointer events, e.g if the map is inside a ListView, the ListView will want to handle vertical drags. The map will claim gestures that are recognized by any of the recognizers on this list. When this set is empty or null, the map will only handle pointer events for gestures that were not claimed by any other gesture recognizer.

2. compassEnabled: This property tells us if the map should show a compass when rotated. By default, the value is set to true.

3. cameraTargetBounds: This property tells us the bounds for the map camera target. It is used with GoogleMapOptions to wrap a LatLngBounds value. This allows distinguishing between specifying an unbounded target from not specifying anything.

4. mapType: This property tells us about the type of Map tiles to display. There are five types of tiles
 — none: Do not display map tiles.
 — normal: Normal tiles with traffic, labels and subtle terrain information.
 — satellite: Satellite imaging tiles (aerial photos).
 — terrain: Terrain tiles (indicates type and height of terrain).
 — hybrid: Hybrid tiles (satellite images with some labels/overlays)

5. minMaxZoomPreference: This property tells us Preferred bounds for map camera zoom level. It’s used with GoogleMapOptions to wrap min and max zoom.

6. rotateGesturesEnabled, scrollGesturesEnabled, zoomGesturesEnabled, tiltGesturesEnabled: These fours properties are responsible for the respective gestures on the map like, rotate, scroll, zoom and tilt.

7. myLocationEnabled: This property tells us whether “My Location” layer should be shown on the map. This layer includes a location indicator at the current device location, as well as a My Location button.

Exploring the GoogleMap Widget:

We got the basic map displayed and we got to know what functionality it can have, let us explore some of the functionality practically here:

Device Location:

Let’s start by displaying the user’s location on the map. In the properties above, we came across a property called myLocationEnabled, this property is responsible to display the user’s location on the map.

  1. Set the value of myLocationEnabled to true.

2. Add location permission to both native platforms of your app.

On Android, add either
 <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” /> or
 <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” /> to your AndroidManifest.xml file. ACCESS_COARSE_LOCATION returns a location with an accuracy approximately equivalent to a city block, while ACCESS_FINE_LOCATION returns as precise a location as possible, although it consumes more battery power.

On iOS, add a “NSLocationWhenInUseUsageDescription” key to your Info.plist file. This will automatically prompt the user for permissions when the map tries to turn on the My Location layer.

So, by writing a few lines of code to set permissions on the native platforms and by setting myLocationEnabled property to true we get the user’s current location.

Changing MapType:

You can change the type of Map by using the mapType property of GoogleMap Widget and can set to any type, satellite, terrain, hybrid or normal.

We also created a tap to switch the mapType using a floatingActionButton, as we know GoogleMap is just like any another widget in Flutter so that means we can use the Map inside other widgets, so we placed the GoogleMap widget inside the Stack and added a floatingActionButton and gave it the functionality to switch the map between the normal and satellite, follow the code snippet to know more,

https://gist.github.com/Aditsyal/6e50ae85d1d1a99749a128ca10096c53#file-maptype-dart

Enable and Disable Gestures:

GoogleMap widget has gestures property in it, namely rotateGesturesEnabled, scrollGesturesEnabled, zoomGesturesEnabled, tiltGesturesEnabled:

https://gist.github.com/Aditsyal/cd5e487cff3e2d7f53463b852f66ef0a#file-googlegestures-dart

Moving the Camera around:

Now, let’s try to move the camera to a specified Latitude and Longitude, for that we use the animateCamera method which animates the change of map position. It takes the CameraUpdate as it’s parameter which has various features in itself, like

newLatLng(LatLng latLng): It moves the camera to a specified geographical location.
newLatLngBounds(LatLngBounds bounds, double padding): It returns a camera update that transforms the camera so that the specified geographical bounding box is centered in the map view at the greatest possible zoom level.
newLatLngZoom(LatLng latLng, double zoom): It moves the camera to a specified geographical location with a zoom level.
scrollBy(double dx, double dy): It returns a camera update that moves the camera target the specified screen distance.
zoomBy(double amount, [Offset focus]): It returns a camera update that modifies the camera zoom level by the specified amount.
zoomIn(), zoomOut(): It moves the camera closer or further away from the surface of the earth.
zoomTo(double zoom): It returns a camera update that sets the camera zoom level.

These are the certain ways of moving the camera around with respective functionality of their own. Feel free to use them as required by you. Here we gonna use newLatLngZoom(LatLng latLng, double zoom) to move the camera to a specified location using a certain level of zoom.

We created a method _goToNewYork in which we used the animateCamera method to animate the camera move on the basis of latitude and longitude of NewYork with a zoom of 10. Then we created a drawer using the drawer property of Scaffold to display it. Let us show you the code snippet,

https://gist.github.com/Aditsyal/59205c109ded25f043478d83ab839c0f#file-movethecamera-dart

So, we can see the animated movement of the camera from one location to another using the latitude and longitude. We created a bunch of other location and put them in the drawer for you to try move to different location. The GitHub link of the module will be provided in the end.

Set the Marker on the map:

Now that we’re able to move the camera around on the basis of specific latitude and longitude, we’ll try to put the marker on the location we move our camera. Let’s suppose you want to move to New York, so when the camera moves to new york you can see a marker set on the particular location.
 To achieve this we’ll use the markers property of GoogleMap widget which takes a set of marker.

https://gist.github.com/Aditsyal/0f0297594e3ff63912113a6b2dbfac5f#file-setthemarker-dart

Now we want the marker to be set as the user moves to the specified location, so we created a marker inside the _goToNewYork method inside the setState() method.

https://gist.github.com/Aditsyal/7d0f293521d085e8e9a6cb32fc79dd21#file-markers-dart

Marker marks a geographical location on the map. Here, the markerId is the unique id of each marker and position property takes the LatLng of the location. This gives us

Now, let’s add some information on the marker so that when it’s tapped the information is displayed. For this we’ll use the infoWindow property of the Marker widget which gives us a title, snippet, to give the title to the marker and desc to the marker.

https://gist.github.com/Aditsyal/d6709ecb54efa5bd2e227a270c7c5120#file-infowindow-dart

Now that we added the marker on the map at our desired location using the latitude and longitude of the place and also gave the marker some text to be displayed when tapped. We just showed the implementation of how to do it, know it totally depends on you how to use it and how to implement it. You can find the complete module on github.

Conclusion:

GoogleMap widget is just like any other widget in Flutter that means this widget can be placed inside any other widget, like Listview, Stack, Column, Row, Container and so on, you can even transform it, clip it but we know why would someone clip it we’re just telling you that you can perform anything on the map as its a widget. So be creative, explore more and even let us know of something you come across.

Do let us know how was the article and wish we could cover everything in the article, every feature but that would just mean writing a book and that’s not what you want and what we want. We tried to explain from the root from how to install it, to some basic feature which you might require in regular use if you’re using map.

Aditsyal/flutter_maps
Google Maps in Flutter. Contribute to Aditsyal/flutter_maps development by creating an account on GitHub.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 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.


Managing the state of a Widget using Provider | Flutter

What is Provider?

A dependency injection system built with widgets for widgets. provider is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward.

Let’s build a very simple navigation app with the Provider package.

We will build a navigation drawer app and when we tap on the item on the drawer the screen replaces with another screen just like Navigation menu fragment transaction.

This is just like a Fragment Transaction in an Android app.

Step 1: Add the dependency in your pubspec.yaml.

provider : <latest-version>

Step 2: Create a Provider class

/media/72482944219ad3fe84e7b3bb2943a8ab

In this provider class, we have implemented our logic which is to update the current navigation value.

updateNavigation will update the current value of the navigation and notify the listener.

To notify, you need to add the ChangeNotifierProvider to the root of the Widget tree.

home: ChangeNotifierProvider<NavigationProvider>(
builder: (_) => NavigationProvider(),
child: HomePage(),
),

Step 2.1: Update the UI

Unlike Bloc, you do not need to use the StreamBuilder to update the UI.

navigation.getNavigation will return the body as declare in the provider class above.

Step 2.2: Update the UI with Consumer

You can also use Consumer to get the value and update the UI then you do not need to use

Provider.of<provider-class>(context);
body: Consumer<NavigationProvider>(
builder: (context, navigationProvider, _) =>
navigationProvider.getNavigation),

Step 3: Add the drawer

/media/834f4d14010bf649ffd6cc2c12994846

Whenever we tap on any drawer item, first it will close the drawer menu using Navigator.of(context).pop()then it updates the provider which changes the navigation value and the provider will update the UI.

/media/e7895e2bdaf6f0cb99ca251d6a54adc4

Now its time to run the app.


We have also linked a repo.

ashishaeologic/Flutter-ProviderExample
Contribute to ashishaeologic/Flutter-ProviderExample development by creating an account on GitHub.github.com

Thanks for reading this article ❤

We got something wrong? Let me know in the comments. We 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.

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


Managing the state of a Widget using bloc | Flutter

It’s very hectic to manage state in flutter it when we have a complex UI and complex widget tree.
Before we jump into the state handling using bloc you need to understand about state management.

Why we need State management

Whenever we perform an operation on the widgets, suppose we have a RaiseButton and whenever we tap on it, it updates the Text, the very simple method is to use the setState(). It is not a problem if you have a small widget tree but you need to avoid the setState() if we have a complex Widget tree.

Why not setState()?

Suppose we have this Widget tree and we need to update only on development in the Widget tree but if we use setState(), it will rerender the whole widget tree and update all the elements.

There are few techniques for managing the state :

InheritedWidget: It allows you to pass the state to its child widgets, to youse the InheritedWidgets you need to add the Inherited widgets at the root of the widget tree but the problem with the InheritedWidget is that state is final when you are using theInhertedWidget so you cannot mutate the state.

Scoped Model: ScoperModel provides a better way to access, mutate and update widget state and it is built on top of InheritedWidget.
If your Model gets complex, it might be challenging to know when to properly call notifyListeners() to avoid unnecessary updates.

let’s talk about Bloc

Bloc

BLoC stands for Business Logic Component. Before we dive into bloc we need you to understand the Sink and Stream.

We add the data into the Sink and listen to the streams of data through Stream and updated the UI using StreamBuilder.

Let’s code

We will build a navigation drawer app and when we tap on the item on the drawer the screen replaces with another screen.

This is just like a Fragment Transaction in an Android app.

Step 1: Create a Bloc

We have created a class which contains a StreamController, StreamControllercontrols the stream of data and we have a Streamwhich will be used in the StreamBuilderto get the data flowing in the Stream.

Step 2: Create a Provider class

In this provider class, we have implemented our logic which is to update the current navigation value.

Step 3: Implement Provider class into Bloc

https://gist.github.com/ashishrawat2911/b83d0a0c78ea75e6a57d7b5c52771d01#file-bloc-dart

Now we have a bloc class which will update the navigation value and sink the value in the stream and uses it in StreamBuilder.

Step 4: Update the UI using StreamBuilder

Now NavigationDrawerBloc bloc = NavigationDrawerBloc();

So we have wrapped the body with StreamBuilder so whenever there is any change in the stream it will automatically update the body.

Add the drawer

https://gist.github.com/ashishrawat2911/edb453caeb8c888372f3f4560488eb29#file-drawer-dart

Whenever we tap on any drawer item, first it will close the drawer menu using Navigator.of(context).pop()then it updates the bloc which changes the navigation value and the data flows through the stream and StreamBuilderupdates the UI.

Make sure you close the stream, we can do is call the dispose method which we create in the bloc class bloc.dispose() .

https://gist.github.com/ashishrawat2911/1ee5434589f60cbc38ad889bfa584adc#file-navigationui-dart

Now its time to run the app.


we have also linked a repo.

ashishrawat2911/flutter_navigation_drawer_bloc
Contribute to ashishrawat2911/flutter_navigation_drawer_bloc development by creating an account on GitHub.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 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.


Using SharedPreferences in Flutter

What is SharedPreferences?

SharedPreferences is used for storing data key-value pair in the Android and iOS.

SharedPreferences in flutter uses NSUserDefaultson iOS and SharedPreferences on Android, providing a persistent store for simple data.

Why use SharedPreferences in Flutter?

Suppose you wanna save a small value (a flag probably) that you wanna refer later sometime when a user launches the application. Then shared preference comes into action.

We do not use SQLite for saving small values because then you will need to write lengthy codes and supporting classes.

Shared Preference let you read and write key-value pair in a couple of lines easily. But always remember, shared preference is not a solution for you to keep complex relational data.

How to use SharedPreferences in Flutter?

Before using SharedPreferences, you should know that Flutter SDK does not have support SharedPreferences but fortunately, the shared_preferences plugin can be used to persist key-value data on disk.

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

dependencies:
flutter:
sdk: flutter
shared_preferences: "<newest version>"

Step 2: Import shared_preferences.dart

import 'package:shared_preferences/shared_preferences.dart';

Step 3: Save data

We can only add int, String, double and bool using SharedPreferences.

There are setter methods in the SharedPreferences class which take two parameters, key and value.

keys are only string values

Saving String value

https://gist.github.com/ashishrawat2911/0cdad3ca524d06a455d0986687567848#file-addstringsf-dart

Saving int value

https://gist.github.com/ashishrawat2911/d57dbfd9fc465cfe1c20f65be725cef2#file-addintsf-dart

Saving double value

https://gist.github.com/ashishrawat2911/bac6897604ac01b544915a3ef25c4aff#file-adddoublesf-dart

Saving boolean value

https://gist.github.com/ashishrawat2911/362c16deae76b40b8d2b357ebc68269c#file-addboolsf-dart

Step 4: Read data

When we are reading the data from the storage through SharedPreferences we only required to pass the key only.

https://gist.github.com/ashishrawat2911/2bc3d85c0a31bd1c2bf9009a8f865f88#file-readvaluessf-dart

If the value is not present in the storage then we might get a null value.
To handle this we can use

int intValue= await prefs.getInt('intValue') ?? 0;

Step 5: Remove data

To remove the data from the storage we provide the key in the remove(String key) method.

https://gist.github.com/ashishrawat2911/e9ba0b8bc3fcf1aae1fe7c2ca78cfc2d#file-removevaluessf-dart

Check value if present or not?

SharedPreferences prefs = await SharedPreferences.getInstance();

bool CheckValue = prefs.
containsKey('value');

containsKey will return true if persistent storage contains the given key and false if not.


Thanks for reading this article ❤

Connect with me on Linkedin and Github

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


BLoC pattern in Flutter | FlutterDevs

By the title, you must have got an idea about what this article will be. As Flutter is growing day by day and so it’s developers and we as a developer always look for an easy way to deal with the code. So as the title speaks out loud we’ll be covering BLoC pattern in detail answering various questions like,

What is BLoC Pattern?
 Why BLoC?
 When to use BLoC?
 and, How to implement BLoC?

But in this article, we’ll only be covering the first three questions in detail and the very next article will solely feature BLoC implementation with an example.

What is BLoC pattern?

BLoC a.k.a Business Logic Components is a design pattern presented by Paolo Soares and Cong hui, from Google at the DartConf 2018.
Initially, BLoC pattern was conceived to allow the reuse of the very same code independently of the platform: web application, mobile application, back-end. So yeah, this pattern was developed aiming to ease the workload on developers end while developing apps for a different platform with the idea of code reusability. Watch the video below to get more insight on the baby steps set by BLoC.

So, if you watch this video then you will understand how using BLoC you can share most of your code to different platforms.

To know BLoC in detail let’s first get to know about Streams.

Streams

In a general sense, a stream is a continuous flow or succession of anything.
 For example, this is a stream of cats 😛

https://cdn-images-1.medium.com/max/720/1*ccPKTUTwZtt8HADzCtBLwA.gif

But technically speaking, Stream is nothing but a continuous flow of data.
 Let’s take an example of Conveyor Belts. A Conveyor Belt has two ends, from one end an item is passed(input), then it is processed and after processing, it gets out from another end of the belt(output).

Key terms:

  • Stream, the conveyor belt is called as a stream
  • StreamController, this is what controls the stream
  • StreamTransformer, this is what processes the input data
  • StreamBuilder, it’s a method that takes stream as an input and provides us with a builder which rebuilds every time there is a new value of a stream
  • sink, the property which takes an input
  • stream, the property which gives the output out of the Stream

So now we got a bit of an idea about Streams. Back to Flutter, I think the one of the main hindrance one comes across while coding in Flutter is to deal with UI and everything else as in Flutter we don’t have any intermediatory designing language for the UI like in Android we have XML, instead in Flutter we write all the code at one place(traditionally). That’s where BLoC comes in play and helps remove this hindrance in an efficient way.

  • BLoC not only solves the code sharing problem but also leverages Streams functionality in order to manage and propagate state changes in Flutter.
  • BLoC helps us to separate Business Logic from UI. In other words, UI components should only worry about the UI and not the logic.
  • So, even though Flutter lacked an intermediatory language for UI using BLoC one can separate both the things making independent on each other.
  • If you’re an Android developer, then think of BLoC object as a ViewModel and of StreamController as a LiveData.

What does all this mean?

As already discussed BLoC makes use of Streams, we can infer the following things,

https://www.didierboelens.com/images/streams_bloc.png
  • The input is taken using the sink property
  • The output is provided using the stream property
  • Widgets send events to the BLoC via sinks
  • BLoC notifies the widgets via streams
  • Now that business logic and UI components are separated, we may change the Business Logic of the app at any time without any impact on the UI
  • Similarly, we may change the UI without having any impact on the Business Logic

Why use BLoC?

Now that you got an idea about what BLoC is, you might be thinking why to use it for state management when there are already a few other ways to deal with it, let’s discuss them and see why BLoC is efficient out of all.

setState()

The setState() method notifies the framework that the internal state of the object has changed. Whenever you change the internal state of a State object, make the change in a function that you pass to setState:

setState(() { _myState = newValue } );

Calling setState notifies the framework that the internal state of the object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

Problems with this:

  • The whole widget tree gets rebuilt every time state of even a single widget changes.
  • It doesn’t help to separate the UI components and Business logic.

InheritedWidget

It is a special kind of a widget that defines a context at the root of a sub-tree and can efficiently deliver this context to every widget in that sub-tree.

As said, it can

  • Propagate data down the tree
  • Update widgets on rebuild

Problems with this:

  • The state is set to final which means it is immutable.
  • It doesn’t provide any dispose method to free the resources and to avoid data leaks.

Scoped Model

It is an external third party package maintained by Brain Egan. It is built on top of InheritedWidget offering a slightly better way to access, update and mutate the state. It allows you to easily pass a data model from a parent widget down to its descendants and also rebuilds all the children that use the model when the model is updated. To check for any change a method notify listeners() is used by Scoped Model.

Problem with this:

  • As the model gets more complex it’s hard to keep track of when you should call notifylisteners().

So, all the above-mentioned approaches have one or the other demerits which didn’t stand as the best way of state management in FLutter and that’s where BLoC pattern stands to be efficient as it deals with all the demerits of these approaches.

Watch the video for a better perspective,

When to use BLoC?

To get to know when to use BLoC and when not to use, we must be aware of the concept of Local state and Global State.

Local State vs Global State

Taking an example you might have used: Imagine a login form, where the user has to enter the username and password and then there is an API communication to validate the credentials of the user upon which authentication works. So here and form of validation on the login form is considered as Local state since its scope is applied to this component only and the rest of application has nothing to do with it. While the API communication upon which the authentication of the user was depended is considered as Global state since it’s upon this authentication the entire scope of the app is dependent.

So, the basis on this local state and global state scope of the different methodology is dependent, see the table to know more.

Redux is also a state management approach. For dealing with local state BLoC is best recommended, while for Global state BLoC maybe used when the app is simple and not much complex but not recommended. For Global state, Redux is highly recommended.

So, this article gives you the necessary details about BLoC, from what is BLoC, why to use BLoC and when to use BLoC, the last question i.e How to implement bloc will be covered in a totally different article where Login form authentication will be performed using BLoC.

We hope this article was helpful to you and if there is something that we left then do let us know in comments and also if you want something else for us to cover in Flutter.

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

Concurrency In Flutter

0

Concurrency is pivotal in versatile application advancement since it permits an application to play out numerous errands at the same time without obstructing the fundamental thread. Flutter’s customizing language is Dart, which is single-threaded of course. This implies it executes in a solitary thread. In any case, on the off chance that we work on a huge application with central processor escalated tasks, the principal thread might turn out to be slow, influencing the application’s performance.

In this blog, we will explore the Concurrency In Flutter. We will l take a gander at how to foster enormous applications without sacrificing performance in your 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::

What is concurrency?

Importance of Concurrency In App Development

What is an isolate?

How do they work?

Example 

Conclusion



What is concurrency? :

Concurrency alludes to the most common way of managing many tasks without a moment’s delay. It includes coordinating and executing numerous tasks over time, however not dependably simultaneously. In software development, it implies executing a few calculations or cycles simultaneously, which can essentially work on the performance and responsiveness of users.

Concurrency includes dealing with numerous tasks by exchanging between them, giving the deception that they are running at the same time. This is especially significant in conditions where assets like CPU and memory are restricted, like mobile devices.

Importance of Concurrency In App Development:

The importance of concurrency in app development is:

  • Responsiveness: Mobile applications need to stay receptive to client collaborations. Without concurrency, long-running undertakings like network requests or information handling can obstruct the main thread, causing the application to freeze and giving an unfortunate client experience.
  • Performance: Proficient concurrency takes into consideration better asset use, guaranteeing that undertakings like getting information, handling pictures, or dealing with client input are performed flawlessly without over-burdening the framework.
  • Battery Duration: Appropriate administration of concurrency can prompt better battery use by enhancing how undertakings are planned and executed, lessening pointless CPU utilization.
  • User Experience: Clients expect portable applications to be quick and responsive. Concurrency guarantees that foundation undertakings don’t slow down the smooth activity of the application’s UI, giving a consistent encounter.

What is an isolate?:

Isolates in Dart are an extraordinary method for running different errands simultaneously without dialing back the main thread or freezing the UI. They are especially valuable for running errands that require a great deal of handling power.

Isolates have their own memory store, and that implies they don’t impart memory to the fundamental string or other isolates. This assists with forestalling normal issues that can happen when various strings access shared memory, for example, race conditions or deadlocks.

This isolation guarantees that there are no race conditions or need for synchronization, making simultaneous programming more secure and more clear. Each separate has its own occasion circle and microtask line, permitting it to execute undertakings freely of the primary seclude (the fundamental string).

How do they work?:

Dart utilizes isolates to establish a different execution climate that can run lined up with the principal thread. This considers simultaneous programming by empowering various isolates to run simultaneously, each with its own memory heap, event queue, and event loop. Accordingly, isolates can perform free errands without offering memory or state to other isolates.

  • Isolate Creation: In Dart, you can make a new separate by conjuring the Isolate.spawn() capability. This capability requires two contentions: a high-level capability or a static technique that fills in as the section point for the function, and an underlying message, which is generally a SendPort object. The SendPort object is utilized to lay out a correspondence channel between the recently produced isolate and the spawning isolate.
  • Communication through Message Passing: Isolates don’t share memory space, which guarantees that each disconnect has its own stack and forestalls direct admittance to another segregate’s information. To permit communication between isolates, Dart utilizes a system known as message passing, which includes SendPort and ReceivePort objects. A SendPort communicates messages to another segregate, while a ReceivePort gets messages from another isolate. Messages are passed by value, not by reference, implying that a duplicate of the information is sent, guaranteeing that the first information stays unaltered and secure in its own isolate.
  • Execution of Tasks: Each isolate has its own occasion loop and occasion queue. When a disengage gets a message, it’s additional to its occasion queue. The occasion loop then processes these messages individually by executing the related tasks or capabilities. This cycle goes on until the occasion queue is unfilled or the isolate is ended. This component empowers simultaneous task performance, which helps the proficiency of your Dart and Flutter applications.
  • Termination of Isolates: An isolate can be ended in two ways: automatically utilizing the Isolate.kill() technique, or naturally when it has finished every one of the tasks in its occasion queue. In certain circumstances, a particular message can be shipped off the isolate, training it to end itself.

Example :

In the accompanying code, a new isolate is made to compute the amount of a list of a million numbers. The sumNumbers capability, which is the section point for the isolate, gets the list of numbers and a SendPort for correspondence with the fundamental isolate. It works out the aggregate and sends it back to the fundamental isolate. The primary isolate tunes in for the sum, prints it, and afterward ends the isolate and shuts the ReceivePort.

import 'dart:isolate';

void sumNumbers(List<dynamic> data) {
List<int> numbers = data[0] as List<int>;
SendPort sendPort = data[1] as SendPort;
int sum = 0;
for (int number in numbers) {
sum += number;
}
sendPort.send(sum);
}

void main() async {
ReceivePort receivePort = ReceivePort();
List<int> numbers = List<int>.generate(1000000, (index) => index);
Isolate isolate = await Isolate.spawn(sumNumbers,[numbers, receivePort.sendPort]);
receivePort.listen((message) {
print('Sum: $message');
receivePort.close();
isolate.kill();
});
}

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

Sum: 499999500000

Process finished with exit code 0

Conclusion:

In the article, I have explained the basic structure of the Concurrency in flutter; you can modify this code according to your choice. This was a small introduction to Concurrency in flutter 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 Concurrency In Flutter in your projects. We will show you how isolates can handle heavy computation tasks in a separate thread to keep your app running smoothly. We also provided an example of when it’s appropriate to use isolates in your 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 Facebook, GitHub, Twitter, 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.