Google search engine
Home Blog Page 58

DataTable In Flutter

0

For Mobile App Developers , Displaying data in tables is an everyday task with laying out all the row & columns with appropriate needed space for the same. Displaying Information In Tabular is Easy to Understand & Interpret By the Users by providing More Information In Less Space with proper categorization also. Flutter possesses in its store a widget to perform this task with ease & perfection Using DataTable.

DataTable widget allows you to build a table that automatically sizes its columns according to what’s actually in the cells.

For more info on DataTable ,Watch this video By Flutter :

Note: Use DataTable iff you have fewer rows, because DataTable takes twice the computation for laying out elements on User Interface.


What is Flutter ?

Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time

If you want to explore more about Flutter, please visit Flutter’s official website to get more information.

Flutter Is Proudly Entrusted By These Organizations For their Products : — Flutter Showcase

Click to See Flutter Showcase

DataTable Syntax :

  • : Add the DataTable() widget .
  • : Define DataColumn
  • : Define each DataRow & DataCell in each of it.
DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'Name',
),
),
DataColumn(
label: Text(
'Age',
),
),
......
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Mohit')),
DataCell(Text('23')),
DataCell(Text('Professional')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Aditya')),
DataCell(Text('24')),
DataCell(Text('Associate Professor')),
],
),
....
],
);

Allows Sorting :

  • sortColumnIndex: int typed — The current primary sort key’s column
  • sortAscending: bool value typed — pertains to any value mentioned in sortColumnIndex is sorted in ascending order |or not.
sortColumnIndex : 0 
sortAscending : bool value

Make a Column Numeric :

: numeric — bool valued: represents whether this column represents numeric data or not.

numeric : true | false

Show Selected Row :

: selected — bool valued: represents whether the row is selected or not.

selected : true | false

Show Cell Is Editable :

: showEditIcon — bool valued: represents whether to show an edit icon at the end of the cell.

showEditIcon : true

All DataTable Elements provide friendly-callback to ease out Implementing User behavior to edit, select, sort data with the data cells taking widgets so that you can put in any widgets in your data cells.

Do not forget to wrap with SingleChildScrollView To Avoid any horizontal space overflow in UI .

Using DataTable In Flutter

import 'package:flutter/material.dart';

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

/// This is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';

@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: MyStatelessWidget(),
),
);
}
}

/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
MyStatelessWidget({Key key}) : super(key: key);

@override
Widget build(BuildContext context) {
return DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'Name',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Age',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Designation',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Mohit')),
DataCell(Text('23')),
DataCell(Text('Associate Software Developer')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Akshay')),
DataCell(Text('25')),
DataCell(Text('Software Developer')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Deepak')),
DataCell(Text('29')),
DataCell(Text('Team Lead ')),
],
),
],
);
}
}

When you run this Flutter application, you would get the DataTable displayed in UI as shown below :

DataTable App Demo

Understanding DataTable Elements :

Understand the flutter widgets that play a key role in displaying this Tabular Formatted Data .

DataTable — Possess column & rows which take an array of DataColumn & DataRow Respectively. Each DataRow has cell property that takes an array of DataCell.

  • Both DataColumn & DataCell take widgets as a value so you can assign them Text, Image, Icon, or any other widget.

: DataTable — Renders the DataTable. It possesses properties like — columns , columnSpacing ,dataRowColor ,dataRowHeight,dataTextStyle ,dividerThickness ,horizontalMargin ,key ,onSelectAll ,rows ,runtimeType,showBottomBorder ,showCheckboxColumn , sortAscending , sortColumnIndex

: DataColumn : creates the configuration for a column of datatable . Some Common properties are : label , numeric , tooltip

DataColumn(
label: Text(
'Name',
style: TextStyle(fontStyle: FontStyle.italic),
),
numeric: true,
tooltip: "Enter name here",
),

: DataRow : Row configuration and cell data for a DataTable. It has properties like selected, onSelectChanged to handle select behavior.

: DataCell : lowest level widget in datatable which contains cell level information with widgets as value.

Enabling For Flutter Web

DataTable Performs the Same for flutter web as well by changing the channel to development mode as currently web is enabled in the beta channel.

Use the following commands to switch channels and enabling flutter web

flutter channel beta
flutter upgrade
flutter config — enable-web

Add-On Web to your project & run the project to web view the datatable

flutter create .
flutter run -d chrome

Closing Thoughts

In this blog, we explored the DataTable widget provided by Flutter for rendering data in a tabular grid format. Tables are a Quintessential tool in modern applications as they provide us with the ease of customizing the User-Interface of the app as per user needs. They also provide the app it’s fondness and customizability as per particular needs. The key purpose of this article is to avail you of an Insight of How we can create DataTable based flutter application using the Pagination Technique.

If you have not used DataTable, I hope this article has provided you with content information about what’s all about it and you will give it — a Try.

Initiate using DataTable for your apps. !!!


References For the Blog :

DataTable class
A material design data table. Displaying data in a table is expensive, because to lay out the table all the data must…api.flutter.dev

data_tables | Flutter Package
ListView on Mobile and Stateless Data Tables on Tablets and Desktops.pub.dev


🌸🌼🌸 Thank you for reading. 🌸🌼🌸🌼


From Our Parent Company Aeologic

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

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

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

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

Related: Dialog Using GetX in Flutter

Related: Bottom Navigation Bar using Provider | Flutter

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

www.flutterdevs.com

Hero Animations In Flutter

0

In this blog, we will explore the Hero Animations in a flutter. We will be using some core functions available in a flutter to achieve this without any third party application. We will implement a demo of the Hero Animation in your flutter applications.


Table of Contents :

Flutter

Hero Animation

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time

Hero Animation :

Hero widget is a great out-of-the-box animation for communicating the navigation action of a widget flying from page to page. Hero animation is a shared element transition (animation) between two different pages. Now to See this, Imagine a superhero flying in action. For example, you must have an image list. As we wrap it with a hero tag. Now we tap on an item list. and when tapped. Then the images list item lands its position on the detail page. when we cancel it and come back to the list page, then the hero widget returns to its page.

Demo Module :

Code Implementation

Create a new dart file calledhero_animation_list inside the lib folder.

In this screen use the PageRouteBuilder class to create a custom root. It Provides animation object. The PageViewBuilder has a transitionDuration function that sets animation durations. Builder function is used to create route content add the transition builder function.

Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds:900),
pageBuilder: (_, __, ___) => ListDetail(index: index),
settings: RouteSettings(
arguments: heroAnimationListModel[index],
),
));

The Hero widget is the marked for hero animations. when the naviagator push or pop pageroot,the entire screen content changes.But it displays and resizes from page to another page.

//Hero Animation list page.
Hero(
tag: "ImageTag" + index.toString(),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
),
child: Image.asset(
item.img,
width: _width,
fit: BoxFit.fill,
),
),
),

In this Detail Screen, we have used the same tag of the hero widget from the list page (Main Page) which transitions the hero animation.

Hero(
tag: "ImageTag" + widget.index.toString(),
child: Image.asset(
heroAnimationListModel.img,
fit: BoxFit.cover,
)),

Code File :

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_hero_animation_demo/Constants/constants.dart';
import 'package:flutter_hero_animation_demo/list_detail.dart';
import 'package:flutter_hero_animation_demo/model/hero_animation_list_model.dart';

class HeroAnimationList extends StatefulWidget {
@override
_HeroAnimationListState createState() => _HeroAnimationListState();
}

class _HeroAnimationListState extends State<HeroAnimationList> {
double _height;
double _width;

int _selectedIndex;

List<HeroAnimationListModel> heroAnimationListModel;

PageController pageController;

@override
void initState() {
heroAnimationListModel = Constants.getHeroAnimationListModel();
pageController = PageController(viewportFraction: 6.0);
super.initState();
}

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey[50],
title: Text(
'Hero Animation',
style: TextStyle(color: Colors.black),
),
centerTitle: true,
elevation: 0.0,
),
body: Container(
margin: EdgeInsets.only(left: 20, right: 20),
child: ListView.builder(
controller: PageController(viewportFraction: 0.4),
itemCount: heroAnimationListModel.length,
scrollDirection: Axis.vertical,
//shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return _buildHeroAnimationList(
heroAnimationListModel[index], index);
}),
),
);
}

Widget _buildHeroAnimationList(HeroAnimationListModel item, int index) {
return InkWell(
onTap: () {
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds:900),
pageBuilder: (_, __, ___) => ListDetail(index: index),
settings: RouteSettings(
arguments: heroAnimationListModel[index],
),
));
},
child: Container(
// padding:EdgeInsets.only(left:30.0,right:0.0),
margin: EdgeInsets.only(top: 10.0),
//height:_height/2.9,
//width: _width /20,
// color: Colors.cyan,
child: Column(
children: [
Stack(
children: [
Container(
height: _height / 4,
width: _width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: item.color,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: 110,
child: Hero(
tag: "ImageTag" + index.toString(),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
),
child: Image.asset(
item.img,
width: _width,
fit: BoxFit.fill,
),
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(left: 15.0, right: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Hero(
tag: "TextTagOne" + index.toString(),
transitionOnUserGestures: true,
child: Material(
type: MaterialType.transparency,
child: Text(
item.title,
style: TextStyle(
fontSize: 16.0,
letterSpacing: 0.5,
fontWeight: FontWeight.w700),
),
),
),

Hero(
tag: "TextTagTwo" + index.toString(),
transitionOnUserGestures: true,
child: Material(
type: MaterialType.transparency,
child: Text(
item.subTitle,
style: TextStyle(
fontSize: 13.0,
fontWeight: FontWeight.w600,
color: Colors.black54,
letterSpacing: 0.2),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
),
],
),
),
],
),
],
),
),
);
}
}

Conclusion :

In this article, I have explained a Hero Animation demo, you can modify and experiment according to your own, this little introduction was from the Hero Animation our side.

I hope this blog helps will provide you with sufficient information in Trying up the Hero Animation in your flutter project. 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.

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

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

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

Unit Testing In Flutter

0

Hello everyone, I am back with another interesting topic- Unit Testing in Flutter

So today, I will talk about, unit testing in flutter and give you some examples that you would be able to implement in your apps to test them for better performance in every aspect.


First focus on why testing in flutter is much, much better than testing on IOS or Android native code,

Well for once if you have any experience with UI Automator or Espresso, you might’ve noticed how much time taking they are, They are quite slow and prone to break easily, In-fact many times you would end up searching in your code for what did you mess up while it might just not be your fault,

Not only they are more expensive to run but there is also flakiness in it.

OK, so now let me tell you why flutter’s testing is amazing

(every time I think I cannot fall in love with flutter anymore, It just proves me wrong)

So, Unit Testing, are the type of tests are usually conducted to test a particular method or a class under variety of cases. These tests do not require inputs and don’t have anything to do with rendering anything to screen or even reading/ writing from the disk. These are the simplest tests to perform .

So to perform these we use test statements something like 
test(‘i m testing this feature’) and then you write your code and after that write the expect statement which is basically what you “expect” the code to do.

(the best example I can think of for this is like imagine if you are making a D&D game and well you have a function that generates a random number and according to that number reads out a scenario)

Alright, so now we have studied about Unit Testing lets see how is it done.

So first we move over to test directory in our project

After that we need to import the package

import 'package:flutter_test/flutter_test.dart';

So When you are done importing the flutter test package you need to create void main() and then follow as i do :

void main() {

test('title for your test', (){
// your function body
int a;
int b =5;
int c = 5;
a =b + c;
expect(a, 10);
});
}

So, what we have here is a simple test, earlier I told about how tests are created now we are going to have a detailed look at it and see what is it doing.

so the test keyword is from flutter_test package which helps us test stuff, if takes 2 parameters, first is a String aka the title of your test, the other is basically a function and inside that function you put out what you wanna test

After you are done writing the body of your function now you need to write your expect which is basically what you expect this test to do, so in this case I put in my a at the place of “actual” and then at the place of “matcher” I put in the value I expect a to have when the function ends, simple right?

Now then how do we run tests?

So after writing the test you might’ve noticed a run button next to number of the line you wrote test keyword

So clicking on that will run the test and in the logs you can see whether the test failed or passed

Alright so now we can move on to testing better stuff, so currently I am making a D&D game so I want to put some dialogue when players rolls the dice and lands on a particular number

so to test it, I created a new class called Dialogue and in the class I made a static function that returns dialogue based on what the user rolled,

class Dialogue {
static String dialoguePicker(int val) {
switch(val) {
case 1:
return "You rolled 1, You earned 500 gems, brave adventurer!";
break;
case 2:
return "You rolled 2, You now have to face a monster and win!";
break;
case 3:
return "You rolled 3, You get an extra life, adventurer!";
break;
case 4:
return "You rolled 4, You get a brand new sword brave adventurer!";
break;
case 5:
return "You rolled 5, You get a new shield brave adventurer!";
break;
case 6:
return "You rolled 6, You get a Full HP health potion!";
break;
default:
return " I am sorry adventurer we have ran out of goods at the moment";
}
}
}

So its a simple switch that decides what my NPC says. now lets try to test it out

Right so when you have multiple tests that belong to a particular group its called grouping of tests, so to group them you have to use group keyword which takes a String as title and a function as body

void main() {

group("testing the dialogue generated by user's roll", (){
test("test when user lands 1", () {
int val = 1;
String dialogue = Dialogue.dialoguePicker(val);
expect(dialogue, "You rolled 1, You earned 500 gems, brave adventurer!");
});

test("test when user lands 2", () {
int val = 2;
String dialogue = Dialogue.dialoguePicker(val);
expect(dialogue, "You rolled 2, You now have to face a monster and win!");
});

test("test when user lands 3", () {
int val = 3;
String dialogue = Dialogue.dialoguePicker(val);
expect(dialogue, "You rolled 3, You get an extra life, adventurer!");
});

test("test when user lands 4", () {
int val = 4;
String dialogue = Dialogue.dialoguePicker(val);
expect(dialogue, "You rolled 4, You get a brand new sword brave adventurer!");
});

test("test when user lands 5", () {
int val = 5;
String dialogue = Dialogue.dialoguePicker(val);
expect(dialogue, "You rolled 5, You get a new shield brave adventurer!");
});

test("test when user lands 6", () {
int val = 6;
String dialogue = Dialogue.dialoguePicker(val);
expect(dialogue, "You rolled 6, You get a Full HP health potion!");
});
});


}

So here is the full function, now to run this you just need to click on the run button near the group.

Tests are also useful for situations like when you have a validations class and have to test the response of several validations such as validateEmpty or validateEmail etc.

Now that, that’s done for let’s try something a little more interesting, something everyone has to make in their app — Validations

Now in the lib folder we will create another file called validations, and paste below this piece of code

class Validation {

static String validateEmpty(String val) {
if(val.isEmpty) {
return "the value cannot be empty";
}
else {
return null;
}
}

static String validateEmail(String val) {
if(val.isNotEmpty) {
bool emailValid = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(val);
return emailValid?null:"please enter a valid email address";
}
else {
return "email cannot be left empty";
}
}

static String validatePassword(String val) {
if(val.isNotEmpty) {
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';
bool passVerified = new RegExp(pattern).hasMatch(val);
return passVerified?null:"please enter a correct password";
}
else {
return "passwords cannot be left empty";
}

}
}

Its just a simple class that helps you do validations and returns error message if there is any, Now in this case there are 3 methods,

  1. validateEmpty — to check for any empty values in a textfield
  2. validateEmail — to check for any incorrect values entered in the email textfield
  3. validatePassword — to check that the password entered appropriate

Now to test them we will once again create a group and inside that group we will test, first of all the 1. case of validateEmpty only 2 times, once for checking the it return error and the other for checking in case of no error

so first case would be written like this :

test("test field empty returns error", () {
String result = Validation.validateEmpty("");
expect(result, "the value cannot be empty");
});

and the second case goes like this :

test("test field not empty returns null", () {
String result = Validation.validateEmpty("asd");
expect(result, "the value cannot be empty");
});

Then we will test validateEmail 3 times, once for correct value, second for incorrect value and third for empty

First case :

test("test user input email correctly  returns null", () {
String result = Validation.validateEmail("test@gmail.com");
expect(result, null);
});

Second case :

test("test user input email incorrectly returns error", () {
String result = Validation.validateEmail("test@gmail.com");
expect(result, "please enter a valid email address");
});

Final case :

test("test user not entering email returns error", () {
String result = Validation.validateEmail("");
expect(result, "email cannot be left empty");
});

And now we will test the validatePassword method 3 times as well, where all the cases would be same as validateEmail — correct value,incorrect value, empty

First case :

test("test user entering password correctly returns null", () {
String result = Validation.validatePassword("Pass@123");
expect(result, null);
});

Second case :

test("test user entering password incorrectly returns error", () {
String result = Validation.validatePassword("asddsaasdsda");
expect(result, "please enter a correct password");
});

Final case :

test("test user not entering password returns error", () {
String result = Validation.validatePassword("");
expect(result, "passwords cannot be left empty");
});
  • And since these test belong to the same class we can group them together under “validation tests”.
  • To test non static methods inside the test() you can easily create the instance of the class inside the test() and use it to conduct the tests you wish.
  • The tests written in Unit Testing must be to the point and not very complex so please remember these things when writing tests.

From Our Parent Company Aeologic

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

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

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

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

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

How to use ML Kit in Flutter for 2026

0

Introduction

Machine learning is becoming an essential technology as it can predict the possible outcomes. Through machine learning, we can train our machine and we can make it intelligent so that it can also take decision on its own. It is a subset of artificial intelligence.

With ML Kit we can integrate our app with various smart features such as:

  • Text Recognition
  • Face Detection
  • Image Labeling
  • Landmark recognition
  • Barcode scanning

ML Kit provides us on-Device and Cloud APIs. The on-Device process the data without the use of an internet connection, Cloud provides us high-level accuracy with the use of Google Cloud Platform’s machine learning technology.

In this blog, we shall discuss how to implement Image Labeling, Text Recognition, Barcode Scanner using ML kit. Image Labeling is a machine learning feature that tells us about the content of an image.

So let’s start:

To enable the use of ML Kit we need to connect the app with the firebase. We will be using two dependencies firebase_ml_vision: ^latest version
for ML Kit and image_picker: ^latest version to get the image using a gallery or camera.


Table of Content

:: Resources

:: Configure Your App

:: Creating ImagePicker

:: ImageLabeler function

:: Barcode Scanner function

:: Text Recognizer function


Resources :

firebase_ml_vision | Flutter Package
A Flutter plugin to use the capabilities of Firebase ML, which includes all of Firebase’s cloud-based ML features, and…pub.dev

image_picker | Flutter Package
A Flutter plugin for iOS and Android for picking images from the image library, and taking new pictures with the…pub.dev

Configure Your App

Add the dependencies in your pubspec.yaml

firebase_ml_vision: ^0.9.7
image_picker: ^0.6.7+11

Edit your app/build.gradle

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
api 'com.google.firebase:firebase-ml-vision-image-label-model:17.0.2'
}

Edit your AndroidManifest.xml file

Add the following metadata inside the application section.

<meta-data
android:name="com.google.mlkit.vision.DEPENDENCIES"
android:value="ica" />

Creating UserImagePicker Class:

ImagePicker is one of the most frequently used functionality when we try to get the user images as an input to perform authentication, profile image upload, etc. This widget provides us the flexibility to chose images from our phone gallery or using a phone camera. Here also we are trying to achieve the same.

  • Initializing File and ImagePicker objects
File _pickedImage;
ImagePicker picker = ImagePicker();
  • pickImage function with default ImageSource
void _pickImage(ImageSource imageSource) async {
final pickedImageFile = await picker.getImage(
source: imageSource,
);

How Image Picker will look like?

We will first create a Container that will display the loaded image and a FlatButton.icon, on tapping the button an AlertDialog Box will appear it will show two options Complete action using Camera or Gallery. We can choose either the them.

  • Creating the Image Container

This container with rounded corners shows the image picked by the user. If there is no image then Please Add Image text will be displayed in the center.

Padding(
padding: const EdgeInsets.all(18.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.orangeAccent.withOpacity(0.3),
width: MediaQuery.of(context).size.width,
height: 300,
child: _pickedImage != null
? Image(
image: FileImage(_pickedImage),
)
: Center(
child: Text("Please Add Image"),
),
),
),
),
  • Creating a FlatButton.icon

On pressing FlatButton.icon a AlertDialog will appear that will contain two options to choose from the image source.

FlatButton.icon(
onPressed: () {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text(
"Complete your action using..",
),
actions: [
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Cancel",
),
),
],
content: Container(
height: 120,
child: Column(
children: [
ListTile(
leading: Icon(Icons.camera),
title: Text(
"Camera",
),
onTap: () {
_pickImage(ImageSource.camera);
Navigator.of(context).pop();
},
),
Divider(
height: 1,
color: Colors.black,
),
ListTile(
leading: Icon(Icons.image),
title: Text(
"Gallery",
),
onTap: () {
_pickImage(ImageSource.gallery);
Navigator.of(context).pop();
},
),
],
),
),
);
});
},
icon: Icon(Icons.add),
label: Text(
'Add Image',
),
)

Your UserImagePicker dart file will look like this :

https://gist.github.com/anmolseth06/9c52896eba3c7a43b2ea2dd200366f6a#file-userimagepicker-dart

ImageLabeler :

Creating a imageLabeler function

  • Creating objects for FirebaseVisionImage and ImageLabeler
FirebaseVisionImage myImage = FirebaseVisionImage.fromFile(_userImageFile);
ImageLabeler labeler = FirebaseVision.instance.imageLabeler();

FirebaseVisionImage is an object that represents an image object used for both on-device and cloud API detectors.imagLabeler() method creates an on-device instance of ImageLabeler .

  • Processing image
_imageLabels = await labeler.processImage(myImage);

ImageLabeler provides us processImage() method that takes an FirebaseVisionImage object. Here _imageLables is a list of ImageLabel.

Storing the labels in the result variable.

for (ImageLabel imageLabel in _imageLabels) {
setState(() {
result = result +
imageLabel.text +
":" +
imageLabel.confidence.toString() +
"\n";
});
}
  • processImageLabels() code
processImageLabels() async {
FirebaseVisionImage myImage = FirebaseVisionImage.fromFile(_userImageFile);
ImageLabeler labeler = FirebaseVision.instance.imageLabeler();
_imageLabels = await labeler.processImage(myImage);
result = "";
for (ImageLabel imageLabel in _imageLabels) {
setState(() {
result = result +
imageLabel.text +
":" +
imageLabel.confidence.toString() +
"\n";
});
}
}

Barcode Scanner function :

  • barCodeScanner() function
barCodeScanner() async {
FirebaseVisionImage myImage = FirebaseVisionImage.fromFile(_userImageFile);
BarcodeDetector barcodeDetector = FirebaseVision.instance.barcodeDetector();
_barCode = await barcodeDetector.detectInImage(myImage);
result = "";
for (Barcode barcode in _barCode) {
setState(() {
result = barcode.displayValue;
});
}
}

Text Recognizer function :

  • recogniseText() function :
recogniseText() async {
FirebaseVisionImage myImage = FirebaseVisionImage.fromFile(_userImageFile);
TextRecognizer recognizeText = FirebaseVision.instance.textRecognizer();
VisionText readText = await recognizeText.processImage(myImage);
result = "";
for (TextBlock block in readText.blocks) {
for (TextLine line in block.lines) {
setState(() {
result = result + ' ' + line.text + '\n';
});
}
}
}

Your Main dart file will look like this :

https://gist.github.com/anmolseth06/35cd7d3b4c5480145d4d9f6f1020d057#file-main-dart


🌸🌼🌸 Thank you for reading. 🌸🌼🌸🌼

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.

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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

Camera Plugin with Image Cropper In Flutter

Working with the camera and using it in different apps is quite normal in apps but while implementing it you may face various problems — such as if you are working in an app which is basically an e-commerce app where we need to manage different things we need to select different items and also post our responses with images at that time we must need to write a single code base from where we can manage camera at different locations throughout the app.


So let’s go over its implementation from where we would see how we do that

Implementation:

For implementing we need to add some dependencies

camera: 
image_cropper:
image_picker:
path_provider:

Note: image cropper needs to add a few things in manifest.xml file please look into it. you can find these changes in imageCropper plugin.

Camera plugin for accessing the camera, image cropper for editing the clicked or picked image, path provider for finding commonly used locations on the filesystem, image picker for picking images.

https://gist.github.com/shivanchalaeologic/f9e00f88174e9802d9ea30f2b8f20af2#file-camera_method-dart

Here in the above code, you can easily see that this method is returning a string file by a call back function which is capturedImageFile function by this function we will receive an image which has been clicked or picked by the method.

In this method, we are have created an instance variable of image picker…final ImagePicker _picker = ImagePicker();

and by using this variable we will get the image file through the getImage inbuilt method.

final pickedFile = await _picker.getImage(
source: source,
);

Now we have a file in the pickedFile variable and we need to crop a file like this shown in the image below

val = await ImageCropper.cropImage(
sourcePath: pickedFile.path,
aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
compressQuality: 100,
maxHeight: 700,
maxWidth: 700,
compressFormat: ImageCompressFormat.jpg,
androidUiSettings: AndroidUiSettings(
toolbarColor: Colors.white,
toolbarTitle: "genie cropper",
),
);

In this method ImageCropper.crop Image() different parameters are required where you need to provide your file path, you can provide the ratio in which you want to minimize your image and image’s dimensions as well as you can also set the format in which you want to receive the image.

Later on now after editing that picked image we need to return back the file and we do the same by providing the image to that callback function like this…

capturedImageFile(val.path);

Now the method has returned that image in string format.

Here in the image given below you can see that we have two different buttons by which we are calling two different methods one for the camera and another for the gallery.

onImageButtonPressed(
ImageSource.camera,
context: context,
capturedImageFile: (s) {
setState(() {
_imageFile = s;
});
},
);

We call this method when the button is pressed. Here we are sending different parameters & One of the most is the parameter by which that method gets to know which action is going to take place.

  • For the camera, we use ImageSource.camera and ImageSource.gallery for the gallery.
  • CaputuredImageFile is a callback function bywhich we receive the file and use it according to our needs.

https://gist.github.com/shivanchalaeologic/a4ad36080a9c1ce3a7deb739b87ead54#file-home_page-dart

Conclusion

The fact is there are different ways to access Camera and picking images from the gallery but the most important thing is defining things in the simplest way and working with ease. in this example, I have shown these things in the simplest way I can show if you want to try that out you only need to copy these code files and add these dependencies and it will start working.

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

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

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

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

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

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

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

Face Detection In Flutter

0

Hello Everyone I’m Back again with an exciting article where in we will be developing a flutter application able to detect images using firebase ml kit in our flutter apps .


firstly we will set up the firebase project -:

  • : Go to https://firebase.google.com/ and set up anew project.
  • : After that add in your app and download google-services.json.
  • : Add the lines in build.gradle and then you are done setting up firebase project.

Now we will work with what packages we need in the app :

  • image_picker
  • firebase_ml_vision

These 2 packages are required to work make this particular app

Now, we will go into detail how it works, so Firebase ml_kit has many modals like textRecognizer() , imageLabeler() , faceDetector() etc

Such modals are used to do various tasks (usually self explanatory), We will work with one of these modals to make a face detector app

So the basic idea of app will be for user to select an image from gallery and then we will check the images for faces using firebase_ml_vision package’s faceDetector().

So after your boilerplate code is ready we can start working on getting an image from users gallery,

var imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);

This one line of code allows us to open gallery on click of a button, and we have applied await so that it will wait till the user picks one image,

So onto the next step, we need to convert what we got from image into a FirebaseVisionImage and we can use the .fromFile function from it, which will convert the file image into a firebaseVisionImage type

FirebaseVisionImage fbVisionImage = FirebaseVisionImage.fromFile(imageFile);

After we have a firebaseVisionImage by converting the image picked by user, we will need to initialize a faceDetector which will be done by

FaceDetector faceDetector = FirebaseVision.instance.faceDetector();

Alright after getting the instance of a FaceDetector we can finally work on our logic for the face detection

So we will require a list of Type Face.

Well Face class has many variables such as bindingBox , headEulerAngleY, headEulerAngleZ, leftEyeOpenProbability, rightEyeOpenProbability, we are only going to work with bindingBox which will give us a Rectangle or rather the coordinates of a rectangle around a face, which is what we will use to create a box around that face to show in an image that the rectangular box represents a face of a person

So to do this we need to first let our faceDetector isntance process the firebaseVisionImage and then return to us a list of face.

List<Face> listOfFaces = await faceDetector.processImage(fbVisionImage);

await once again here is important cause it will take time for it to go through the whole image and give us a list of all the possible faces in it.

after getting the listOfFaces, we will then use a simple for loop to get all the bindingBox from it. and then put them into another List which will contain a rectangles, since bindingBox gives us a rectangle.

List<Rect> rectArr = new List();
for (Face face in listOfFaces) {
rectArr.add(face.boundingBox);
}

Note : keep the rectArr outside of this function

So, now we have a list of rectangles that should be drawn on a face, what we need to do now is to simply convert an image into a ui.Image

So we will do that by using the readAsByteSync property of imageFile

var bytesFromImageFile = imageFile.readAsBytesSync();

Now we are going to use decodeImageFromList to get an image from a list of bytes of an image file

You will need to import dart ui as ui

import 'dart:ui' as ui;

After you are done with that, make an ui.Image

ui.Image image;

Note : declare image outside of the function as well

decodeImageFromList(bytesFromImageFile).then((img) {
setState(() {
image = img;
});
});

So after this we are done, with the hard part, now we will move onto the CustomPainter part.

class Painter extends CustomPainter {
Painter(@required this.rect, @required this.image);

final List<Rect> rect;
ui.Image image;

@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.red
..style = PaintingStyle.stroke
..strokeWidth = 7;

if (image != null) {
canvas.drawImage(image, Offset.zero, paint);
}
for (var i = 0; i <= rect.length - 1; i++) {
canvas.drawRect(rect[i], paint);
}
}

@override
bool shouldRepaint(oldDelegate) {
return true;
}
}

We have not done much here just make a class that extends custom painter and its constructor takes 2 parameters first is the ui.Image and the second is List<Rect> a list of rectangles, then we have a method called void paint, which is the main method where you draw,

To draw you first need to declare paint() then give it values such as the width of its stroke and size of the brush, the color of the brush etc, After that we check if the image is empty or not if its not then we tell the canvas to draw the image by using canvas.drawImage() method which takes 3 parameters, one is image which we get when we call painter, second is the offset, we set it to 0, third is the paint we declared earlier.

After drawing the image we now draw the rectangles using another loop and this time we use canvas.drawRect() and in it we pass the rect we get when we call the painter class and the paint.

With this you are almost ready, the final touch up is calling the painter method

For this in the build method we will put this sizedBox as a child

FittedBox(
child: SizedBox(
height: image == null ? height : image.height.toDouble(),
width: image == null ? width : image.width.toDouble(),
child: CustomPaint(
painter: Painter(rectArr, image),
),
),
),

So you must be asking why use fittedbox and sizedBox, well the answer is simple when flutter draws the image you will see the image as magnified and wont be fully contained inside your phone so to fix that we will need to give it bounded height and width and make it fit inside your device.

This will enable user to see the full image in the device.

With that piece of code we are finally done, don’t forget to wrap all the other code in a function and add a FAB that will help us pick images.

See the following gif to get in familiar with the application :

demo gif

For any help, let me know in the comments below, I will try my best to help you out ASAP. Let’s meet in the next article.


From Our Parent Company Aeologic

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

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

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

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

Related: Live Object Detection App With Flutter and TensorFlow Lite

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

FocusNode in Flutter

0

Introduction :

FocusNode basically focuses on the keyboard event. Let’s suppose you want to control the TextFormField widget as soon as the user taps on it, then you use FocusNode. So, FocusNode class is basically an object that can be used to obtain keyboard focus and to handle keyboard events.

Before starting our blog lets quickly access what you will load on your memory after reading this blog

Demo Module

Before starting our blog lets quickly access what you will load on your memory after reading this blog


Table of Content

:: Implementing FocusNode in Forms

:: Creating of FocusNode

:: Usage of FocusNode in a TextFormField

:: Focus a text field when a button is tapped

:: Focus a text field as soon as an application starts

:: Passage of focus on next TextFormField after tapping


Implementing FocusNode in Forms

What is the use of FocusNode?

As we all know that there are many input type TextFormField in our form filling process, we have to input many details in different text area according to its requirement.

When our application has many TextFormFieldand the one which is selected and accepting an input from the user is said to have in a “focus” state. After providing an input to a focused TextFormField our focus now moves to another or says to the next TextFormField area. Here to implement such processes on focusing our selected TextFormField we use FocusNode.

How to focus on a TextFormField when a button is tapped?

Following steps to be performed to focus on a TextFormField

  1. Create a FocusNode.

2. Pass the FocusNode .

3. Give focus to the next TextFormFieldwhen the button is tapped.

How to create a FocusNode?

As you can see above image use the following steps to create a FocusNode instance inside a initState() method of a state class, and clean it up in a dispose() method.

Here we have created a five focus node instance for a different focus area.

How to pass FocusNode to a TextFormField ?

TextFormField(
autofocus: true,
focusNode: fname,
keyboardType: TextInputType.text,
enabled: true,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: 'First Name',
hintText: 'Enter your first name',
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal),
),
),
onFieldSubmitted: (term) {
fname.unfocus();
FocusScope.of(context).requestFocus(lname);
},
)

Here we have used an instance fname of FocusNode in the focusNode property to get focus as soon as the user taps on this Textfield.

How to enable focus on the first TextFormField as an application starts or gets visible ?

We will set the autofocus property as true on that input area or TextFormFieldarea as you can see in the above example. For better understanding look down at an image.

To show the keyboard action when the TextFormFieldis focused we use textInputAction property in the TextFormFeild widget.

Example:

How to pass focus to the next TextFormField when the button is tapped ?

We will use the onFieldSubmitted property inside the TextFormField widget to get unfocus from the current focus TextFormField and get focus on the next TextFormField as soon as the button is pressed or when the keyboard next or done input type is pressed.

In the above example, we have used fname.unfocus() method to get unfocus from the firstTextFormFieldarea of an instance named fname as soon as the button is tapped.

As soon as the button is tapped we have successfully unfocused from the current TextFormFieldbut now we have to move our focus to the next TextFormFieldif available we will use:

FocusScope.of(context).requestFocus(lname)

so as to request our focus on the next TextFormField. We will move to the next TextFormFieldwith the help of the instance, we have created for the next TextFormFieldi.e lname in the above example.

main.dart file :

https://gist.github.com/SooRaj-99/77f625d8bfa68791347b66ee32dc8e3d#file-min-dart

Resources :

FocusNode class
An object that can be used by a stateful widget to obtain the keyboard focus and to handle keyboard events. Please see…api.flutter.dev

Focus and text fields
When a text field is selected and accepting input, it is said to have “focus.” Generally, users shift focus to a text…flutter.dev


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.

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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

Flutter Bloc State Management

A flutter bloc state management series that will walk you through from all the basics of streams to advance state management tools like flutter_bloc/bloc package


Let’s start by understanding what we mean by state management and why should we care about it in the first place.

What Exactly Is State management ?

In simple words, state means data or the current information the user can see or manipulate.

For eg: Interface controls such as text fields, OK buttons, radio buttons, etc. To maintain these state of data like weather a button is pressed or not what is the current text in the text field or is a toggle button on or off, These data which user generally see or interacts with or generates on some event is called the state and the term used for maintaining all these information(state) is called state management.

The problem :

State management can become very messy when the application grows, simple tools like setState in flutter can’t be the solution for managing large changes at once and tools like inherited widget can create a lot of boilerplate code.

The Solution :

To overcome the above problem we can simply use tools like flutter_bloc/bloc these packages are created by the community are pretty useful for reducing boilerplate code and can be very easy to implement.

Before going deep into the flutter_bloc package we need to make our basics clear these basics includes :

  • :: streams
  • :: cubit
  • :: bloc

Streams :

A stream is a sequence of asynchronous data. Streams are just like water hose which have a sink and a drain, Which we can use to provide and retrieve data from streams. To fully understand the concept of bloc we will first need to understand the core features and basic application of streams in Dart.

As we know the basic definition of streams lets generate our own stream using the yield keyword.

using yield to generate stream’s

In the above example, we have a function getRandomNumberStream this function is present in “lib\streamGenerators.dart” (It’s better to clone the repo and take a look at the structure of the program) which output streams we have specified that by using async*. Then we have a Future.delayed() which delays our execution for the first run for 1000 ms and then 500 ms for every other subsequent execution. Then we output(yield) the value.

What yield does it basically output the data in the form of a stream, So this function is going to be our go-to for all our need for streams in this first series.

Now let me brief about all the basic functions that are available with streams.

  • .map: .map helps us to map the event that we are getting from the stream by passing them to a function. ex
StreamGenerators.getRandomNumberStream(10).map((event) => "This event --$event-- is mapped");
op:
This event --$0-- is mapped
This event --$1-- is mapped
This event --$2-- is mapped
This event --$3-- is mapped
This event --$4-- is mapped
  • .take: .take will only take the first N values and drain the rest of the values. ex
StreamGenerators.getRandomNumberStream(10).take(5)
.map((event) => event.toString() + " .take(5)");
op: 
0 .take(5)
1 .take(5)
2 .take(5)
3 .take(5)
4 .take(5)
  • .where: .where this can be helpful in case we want to filter our stream on the basis of some condition. ex:
StreamGenerators.getRandomNumberStream(20)
.where((event) =>
event % 2 !=
0)
.map((event) =>
"$event : filtering stream by eleminating element which are divisible of 2 ")
op:
1:filtering stream by eleminating element which are divisible of 2
3:filtering stream by eleminating element which are divisible of 2
5:filtering stream by eleminating element which are divisible of 2
7:filtering stream by eleminating element which are divisible of 2
9:filtering stream by eleminating element which are divisible of 2
11:filtering stream by eleminating element which are divisible of 2
13:filtering stream by eleminating element which are divisible of 2
15:filtering stream by eleminating element which are divisible of 2
17:filtering stream by eleminating element which are divisible of 2
19:filtering stream by eleminating element which are divisible of 2

There are some other methods which can be useful like expand, transform, etc. You can check out other methods at https://api.dart.dev/stable/2.10.2/dart-async/Stream-class.html.

That’s enough for basics lets tale a look at stream subscription, Stream sink, and stream function.

Stream Subscription: Stream subscription is just like handles to a stream which we can use to control the stream behavior ie. when to stop when to resume and when to cancel. You can check out the StreamSubscription example in the git repo. Let’s take a brief look at stream subscription.

StreamSubscription streamSubscription =
StreamGenerators.getRandomNumberStream(20).listen((event) { }
//accessing methods of stream
streamSubscription.pause();
streamSubscription.resume();
treamSubscription.cancel();

In the above code, we are first subscribing to a stream using the listen method. Then we are accessing the methods of stream subscription. These methods are pretty self-explanatory.

sink: are the opening of the stream where we can input data that we want our stream to consume. Let’s take a look at an example.

final _counterStateController = StreamController<int>();
StreamSink<int> get _inCounter => _counterStateController.sink;
Stream<int> get counter => _counterStateController.stream;

In the above example, we have created a StreamController and accessing its sink and stream functionality using the StreamController object. You can check more about streams and basics of how bloc implements it for its use in the below video though we will be looking at the community package for bloc like flutter_bloc in the next article.


From Our Parent Company Aeologic

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

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

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

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

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

See How Enriched Is Dart ?

0

Dart and its dynamism are one of the hot topics among developers these days, Since its release in 2007 to till now has been improved simultaneously. Basically, Dart is an open-source programming language that is used for different platforms like developing mobile applications, web, server, desktop, and also for Internet of things(IoT) and it is also declared “Standard ” by Ecma.

It was an introduction that everyone knows but the point of discussion is why and how dart is better (if it is) in different fields if we compare to different languages like java, javaScript, swift.


I am saying this because there are different aspects of Dart which either correlate or totally differ from other languages used for mobile application development.

Dart is an object-oriented language and gives a feel like c and if you are familiar with c or java you will be productive and proficient in the dart. However, when the dart is used in a web application it is transpiled (TRANSlate comPILER) in javascript.

The Dart installation comes with a VM as well to run the .dart files from a command-line interface. The Dart files used in Flutter apps are compiled and packaged into a binary file (.apk or .ipa) and uploaded to app stores.

Some Frequently asked questions are addressed by dart.dev itself you can visit to.

If you are trying to identify the language you use is different, better, equal, or a little less in different aspects then you need to make comparisons with others so we will see some small points and decide where Dart lies on ???

So for that, we will take a glance at the languages which are used widely for backend and frontend(not all some of them like javaScript). As you know that when react-native was introduced by Facebook the demand for javaScript went all-time high and swift has also its separate user base.

  1. Dart can be compiled both AOT and JIT which helps building apps in several ways as using JIT compilation can speed up development and AOT compilation can be used during the release process for better optimization. This technique has been used in Flutter app development
  2. Dart coding looks like most ALGOL languages such as C, java so there is not a big difference in syntax, that makes anyone able to learn easily. Things like the Flow of statements such as loops, conditions, breaks are similar.
  3. Abstraction works in a similar manner, allowing abstract classes and interfaces.
  4. if you are familiar with java you know that you need to declare everything explicitly like which type of String, int, etc but in dart you need not do that it refers according to values nature.
  5. In Dart, all data types are objects including numbers. si if you don’t initialize then the value will be counted null not Zero.
  6. All data types are objects, including numbers. So, if left uninitialized, their default value is not a 0 but is instead null.
  7. It has a new inbuilt data type called Runes, that deal with UTF-32 code points in a string. For a simple example, see emojis and similar icons.
  8. Dart also has inbuilt libraries installed in the Dart SDK, the most commonly used being:
  • dart:core for core functionality; it is imported in all dart files.
  • dart:async for asynchronous programming.
  • dart:math for mathematical functions and constants.
  • dart:convert for converting between different data representations, like JSON to UTF-8.

Reason For using in the flutter

These are some key points( mentioned above) but for an app, this is not an end, and Dart also keep surprising user by its some features like

In Dart handling of transition and animation is quite handy because it runs 60 fps, garbage collection object allocation is like javaScript. In dart preemptive scheduling and shared memory is avoidable. That makes it so much faster.

Visualization is easy with the dart in Flutter because the whole layout in one language and at the same place makes it easy to handle and responsive while in others XML or JSX needs to use a separate visual interface builder. Dart is particularly easy to learn because it has features that are familiar to users of both static and dynamic languages.

A New Approach for Programming

Using Dart in flutter is not too different however it is a static-typed OOP language, most important feature is a hot reload that helps to read and compile interfaces easily and fast. In android java and for iOS swift is being used. There is no declarative syntax akin to .xaml files in Xamarin Forms or .nib in iOS. Everything is defined by creating Dart code for widgets and the icing on the cake is Dart formatter (a dart plugin) which helps to format code on a single right-click and the code is up to date.

Conclusion

Basically, this article was not about comparison with any other language but sometimes it is required to give references for others to identify some good or bad features. Dart is no doubt best in some aspects like in compilation of code and it is still improving and there is always a scope of improvement if a community is asking for. so that was a small elaboration of few features which I know about Dart.

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

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

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

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

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

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

Related: Metadata Annotations in Dart

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

CustomScrollView & Slivers In Flutter

0

Introduction :

Appbar is basically a pre built widget inside Scaffold class which is placed as a fixed-height widget at the top of the screen. For scrollable appbar we use a SliverAppBar which embeds an appbar in a sliver for use in a CustomScrollView


Table of Contents:

:: SliverAppBar (scrollable appbar)

:: CustomScrollView

:: SliverFillRemaining class

:: SliverList


SliverAppBar Class

It is an appbar that can be integrated with a CustomScrollView. SliverAppBar is mostly used as a first child of CustomScrollView, which allows the appbar to integrate with a scrolling effect so that it can vary its height up to a certain expandable limit.

CustomScrollView:

Let’s, not bit get confused about CustomScrollView. It is basically a scroll view that creates custom scroll effects using slivers. It provides you with slivers to create various scrolling effects, such as lists and a grid with SliverList and SliverGrid.

Let’s Start: :

How to implement -:

In the body, we have defined the CustomScrollView widget which has slivers as its property which provides various scrolling effects. SliverAppBar widget is used for scrolling appbar up to a certain expandedHeight.

Here we have given an expanded height of 200 which is a given height up to which appbar will scroll down, floating effect is set as false as you do not need to set it as false as its a default value but when you want your appbar to appear while scrolling even you have not reached to the top of the list then set it as true, set pinned property as true if you do not want appbar to disappear while scrolling or set it as according to your need but remember you do not compulsory need to set is as false as is it’s the default value.

FlexibleSpaceBar class is a part of appbar that expands, collapses, and stretches. It is used to set an inner functionality of an appbar which includes title, background, and many more.

=For more Info :

FlexibleSpaceBar class
The part of a material design AppBar that expands, collapses, and stretches. Most commonly used in in the…api.flutter.dev

Till now our appbar is shown to us, but wait we are still not able to scroll down our appbar as it does not show any movement to us. But why?

Because till now, we have not provided other slivers(or any scrollable part ) to our rest filling area, so it is not able to scroll down anything.

Scrollable Part: Other slivers may include such as SliverList, SliverGrid, and SliverFillRemaining, etc.

ANow we going to fill our rest sliver zone area so that our appbar scrolls.

Lets Code: :

How to implement -:

We have filled our other sliver part with SliverFillRemaining class so that our scrolling starts performing.

SliverFillRemaining class

SliverFillRemaining class is a widget inside slivers that contain a single box child that fills the remaining space in the viewport.

Here we have used SliverFillRemaining class so that it becomes a scrollable child. We have provided some text data in column form in this class just to fill up our area so that our appbar starts scrolling.

Now our app looks like this as shown below :

Try it out, now you are able to scroll your appbar accordingly 👍

Let’s understand more :

Description :

The picture looks quite simple and its implementation is as easy as it looks…😊

The above picture contains an appbar that is scrollable and it’s a normal appbar that does not expand its size but float while scrolling.

Above we have seen that only SliverAppBar does not scroll if it is not provided with other scrollable slivers such as SliverFillRemaining, SliverList, and SliverGrid, and many more.

You have already seen how to implement SliverFillRemaining. Here you can see a list type structure in our body area, so I think you must have already guessed that we will be implementing SliverList here.

Lets Code :

Lets again start with building an appbar:-

You have already seen its explanation above, but only the basic difference is here we have not provided expandedHeight to our appbar as we do not want our appbar to expand more..!

Appbar is created till now and it will not scroll and I think we must have understood why?

As I have already explained above for scrolling it also requires scrollable slivers for something to scroll.

Lets code for it :

SliverList

SliverList is a sliver that places multiple box children in a linear array along the main axis. It is just similar to the list view.

For more info :

SliverList class
A sliver that places multiple box children in a linear array along the main axis. Each child is forced to have the…api.flutter.dev

It has one delegate property which is its required property. A delegate that supplies children for slivers. Rather than receiving their children as an explicit List, they receive their children using a SliverChildDelegate.

For more info :

SliverChildDelegate class
A delegate that supplies children for slivers. Many slivers lazily construct their box children to avoid creating more…api.flutter.dev

Inside a SliverChildListDelegate, we have created a list in which loop executes from 1 to 100, and each time its execution takes place it just creates a new widget in list form. Here we have used the ListTile widget which has child property of leading and title. It will create a 100 ListTile widget in a list form that works as a scrollable child or slivers.

So now you can see your appbar starts floating accordingly you scroll down your list and it looks the same as shown in our starting picture….👏

Hope you have enjoyed learning with us…

Refer to the below blog to build a highly custom appBar in Flutter.

Custom AppBar in Flutter
Building a beautiful AppBar using Fluttermedium.com


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think is required…✔

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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