Google search engine
Home Blog Page 32

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.


Animations in Flutter — Getting Started #1

0

Introduction

Animations in a mobile app adds interactivity to the UI as well as some visual effects to it. Animations, when used correctly, can make a huge difference in how user perceives your app. Every mobile developer wish to add animations in their app, but, they are unsuccessful in doing so, because, there is a lot of complexity and lot of things, a developer has to learn before adding animations.

That’s where Flutter comes in…

Flutter has a very good Animation library that allows you to create complex animations that can run constantly at 60 frames per second very easily.

Overview

In this blog post, I’ll tell you about basics/foundation animation concepts in Flutter that allows you add complex animations very easily.

1. Animation Class

All the animations in Flutter are provided by Animation class. According to the documentation, Animation contains a generic type variable Animation<T> which means that what type of value should should be animated. Most common type of Animation used is Animation<double>

To create and run the animation, we need Animation and AnimationController objects. We’ve seen the Animation class in the above section. In the next section, Let’s see the AnimationController class

2. AnimationController

It is basically a controller for animation, which lets you to perform various operations with the current animation

  • Play an animation either in forward or in reverse direction.
  • Pause current playing animation
  • Stop current playing animation
  • Define range of animation — min and max value

https://gist.github.com/flutter-devs/e08e375c0684b571ecbfb7bb3dbad622#file-home-dart

  • In line 7, we are providing SingleTickerProviderStateMixin with the _HomeScreenState class which basically means that we are providing Ticker with the help of SingleTickerProviderStateMixin class and linking it with this class.

Ticker is nothing, but a class which sends a signal at almost regular interval (e.g. Like watch ticks at every second). At each tick, the Ticker invokes it’s callback method(s)

  • In line 14, object of AnimationController is initialised, and it expects 2 parameters — vsync and duration

vsync property binds the AnimationController object with the Ticker and duration specifies the time till which given animation will run.

  • In line 15, we’re attaching the listener with AnimationController object and calling setState() which ensures that, each time the value changes, the Widget is rebuilt
  • In line 18, animation is started using forward() function provided by AnimationController
  • At last, make sure to dispose the given AnimationController object in dispose() method.

Now, you understood the basic concepts of Animation, now, Let’s see the different types of animation

Basic Types of Animation

  • Tween
  • Curved

Tween Animation

Tween Animation is the type of animation which interpolates between the given range. It linearly interpolates between the begin and end value. In the case of Animation<double>, it linearly interpolates between only double values, but, in the case of Tween, it can interpolates between colors, borderRadius, etc.

https://gist.github.com/flutter-devs/f69c3fec53107e7dd96f606d09072729#file-home-dart

In the above code, Tween animation is initialised by giving it’s begin and end value. In this case, we’re specifying 0.0 and 1.0 for begin and end respectively that means it’ll linearly interpolates between 0.0 and 1.0 values and at last, call the animate method and specify the type of animation inside it.

If you want to interpolate between BorderRadius, then, either specify BorderRadiusTween or Tween<BorderRadius>

https://gist.github.com/flutter-devs/33df4af5be42b43b15ba9edd01501e0f#file-home-dart

CurvedAnimation

CurvedAnimation is the type of animation which applies curve to the animation. It provides many different types of curves such as easeIn, fastOutSlowIn, easeOut, bounceIn, and many more. Animation applied through CurvedAnimation follows non-linear curve.

To have a better visual look of different types of curves, head over to this
link

https://gist.github.com/flutter-devs/162d4585c70e71b7db7d78ac0800654f#file-home-dart

First, initialise the AnimationController and after specifying the range of animation with the help of Tween, then specify the CurvedAnimation. CurvedAnimation expects two parameters which are required and one optional parameter —

  • curve: It denotes the curve that is to be followed by animation while the particular widget is animating
  • parent: It links the AnimationController with the Animation
  • reverseCurve: It denotes the curve that is to be used in reverse direction

We got something wrong? Mention it in the comments. We would love to improve.

If you learnt even a thing or two, clap your hands 👏 as many times as you can to show your support!

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.


Developing Web Apps Using Flutter

0

Flutter was introduced back in May 2017 with the general idea of Cross-Platform app development initially for Android and iOS and aiming for Web and Desktop platform. It’s been quite a while when Flutter for Android and iOS went into stable version and even more since the first mention about using Flutter for the web. Earlier the project was codenamed HummingBird but at the Google IO earlier this month, Flutter for Web was made public as Technical Preview aiming to build highly interactive and graphics-rich content for the web. While releasing Flutter 1.0 on Dec’18 the Flutter team disclosed their further plan and goals in Flutter which involves making Flutter build apps for web and can be read from their Roadmap.

Flutter for web is a code-compatible implementation of Flutter that is administered using the various standard web technologies like HTML, CSS, and Javascript. One interesting thing that amuses me is the fact that one can reuse the existing Flutter code to be deployed into any web server, all the features of Flutter and you don’t even have to use any browser plugin.

Things to cover in this article:

  1. Overview of Flutter for web
  2. Creating your First web project
  3. Limitations

Overview of Flutter for Web

So, Yes! Flutter being officially released for the web takes development using Flutter beyond mobile platforms, initially what was restricted just to mobile platforms has now spread its wing across the web and desktop (Linux, Window and MacOS, which we’ll talk about in another article).
Let’s understand the structure and see how Flutter works beneath the hood and compare it with the structure of Flutter for web.

Flutter architecture

So, this is the Flutter architecture for iOS and Android,

  1. The first layer in the structure is Flutter framework layer which is responsible for all the built-in widgets and gestures.
  2. The next second layer is the Flutter engine which is written in C++ and uses Google’s Skia as a graphics library.
  3. Then there is a thin runner layer which is responsible for running the app on individual platforms.
  4. And the last layer is the hardware layer which provides the necessary hardware where the app runs.
Flutter for web Architecture

Now, let us see the architecture of Flutter for Web,

  1. The first layer is similar to the general Flutter architecture consisting Flutter framework layer which is responsible for all the built-in widgets and gestures.
  2. The Flutter engine has been replaced with Flutter web engine which is a lower level implementation of Flutter widgets and rewritten them. It generates dart code which is converted into HTML and CSS.
  3. Dart2js compiler is used to compile the code into javascript which is ready to run on your browser.

Look at the diagram below to have a more detailed and vivid view of the internal working of the web architecture.

Creating your first web project

Now, that we understand the gist about how the Flutter web works or what’s actually happening underneath the hood, let’s move forward and set up our IDE for the web project.

Installation:

Here is the step by step approach of how to create your basic web project:

  1. First, you need to make sure you Flutter version is 1.5.4 or higher and Dart 2.3 must be installed.

flutter channel master && flutter upgrade

2. To make sure that your Flutter is updated, run the following command

flutter doctor

3. Next, you need to add the .pub-cache/bin to your PATH as you will be installing a global package:

For Windows:
C:\Users\<your-username>\AppData\Roaming\Pub\Cache\bin

Restart your system.

For Linux:
$HOME/.pub-cache/bin

For MacOS:
$HOME/flutter/.pub-cache/bin

First Web Project:

  1. In VSCode use ctrl+shift+p to open the command palette and type,

Flutter:New Web Project

2. VSCode will ask permission to install the stagehand, stagehand is a Dart project generator. Accept it and the VSCode will automatically install the stagehand and if you want to install it manually then type the following command in your terminal,

pub global activate stagehand

3. Then, give the name and project location to your project and stagehand will generate a basic project ready for you.

4. It will automatically run pub getcommand to load the necessary packages for your project.

5. To run the basic project you’ll need to install the webdev, normally the VSCode will ask for the permission to install webdev automatically but if you want to install it manually then type the following command in your terminal,

pub global activate webdev

6. To run the project type the following command in the terminal

webdev serve

Basic web project

Understanding the Project Structure:

Let’s see the basic project structure of Flutter for Web project,

Project Structure

The structure has the following components:

  1. dart_tool directory
  2. lib directory
  3. web directory
  4. other basic necessary files required by the flutter

lib directory:

lib directory

The lib directory is what contains all your code just like your normal Flutter project, it has a main.dart file which is just like any main function in Flutter. All the code required for the Flutter app goes inside this directory.

web directory:

web directory

The web directory has two files namely,
1. index.html:

index.html

This is the starting point of your application which loads the application.

2. main.dart:

web/main.dart

The main file in the web directory is the starting point of Flutter web application. This file calls the main method of the lib directory which contains all your code after initializing the engine.

Using assets in Flutter web application:

When you create a web project, the project structure doesn’t include any assets folder and if you try to run any pre-existing application you might come across a situation where your icons won’t be visible. 
The assets folder has to be inside the web directory of the Project.

assets

For your application to display all the icons you must include FontManifest.json file contains all the fonts and icons required by your app.

import ‘package:flutter_web/material.dart’;

Limitations:

Even though Flutter announced the Flutter for web, it is still in Technical preview stage. You can do a lot of things but since it’s still in the early stages there are chances that things can change and as a developer, it will take time for you to explore it without any limitations.

  1. As you may have noticed that you aren’t importing import 'pacakage:flutter/material.dart';instead you’re importing import 'package:flutter_web/material.dart';.This is due to the fact that flutter_web is a forked repository of existing flutter framework. This is the temporary fork and will be merged into one soon.
  2. Plugins are not yet supported completely.
  3. As its just the beginning, the performance might be slow.
  4. Restrictions on the support of all Flutter APIs.
  5. Hot reloading the web page involves a trick. Either you have to manually refresh the web page or use the terminal command to Hot reload webdev serve --auto restart.

So, We hope that you were able to create your first basic Flutter project for web and it runs successfully. You may need to handle the screen responsiveness of your app to deal with different screen sizes. We have a small module related to Flutter for web, you can view it from here.

To watch the I/O video related to Flutter for web,

We hope you liked the article and if there is something you wanna convey then you can reach us at flutterdevs.

You can also read our related articles:

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

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.