Google search engine
Home Blog Page 47

Crashlytics In Flutter

0

Flutter & Firebase have both Transformed into an Omnipotent Integral part of the Developers Community corresponding to their Innate Ability of Never-Ending Scope of Development Covering Multiple platforms like — Android, iOS, Web, and Desktop Apps with an Incessant Dire focus on Making Performant Apps. While both of them have made their Introduction recently, They have gained Immense Popularity & Acceptance in a flash and are now widely trusted by the largest apps around the globe 🌐.

App Stability is a Prominent Factor that can obstruct the success of even the Best Apps. Apps with Bugs can be really frustrating that may tend to make the users UnHappy Culminating to App Uninstalls, Bad App Store Reviews, or a Negative Social Media Feed explaining the Bad Experience that may In turn affect the brand image.

This might would have surely encouraged you to make your Apps Bug-free but a varied kind of crashes can be generated in apps making it difficult & Time-Consuming to manually track them So that you can prioritise which crashes to troubleshoot and fix first.

Firebase Crashlytics helps By Automatically collecting, Analyzing, and Organizing Crash Reports so that we can prioritise Important Issues firstly Keeping our Users happy.

In This Article : The Focus will Be Mainly on Integrating Firebase Crashlytics In Your Flutter Apps


Table of Content :

:: Flutter — Introduction

:: Firebase — Introduction

:: Firebase Crashlytics — Introduction , Key Capabilities

:: Firebase Crashlytics — Implementation Pattern

:: Firebase Crashlytics — Setup Initial Configuration

:: Closing Thoughts


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

What is Firebase ?

Firebase is Google’s mobile platform that helps you quickly develop high-quality apps and grow your business

Firebase is a powerful platform for your mobile and web application. Firebase can power your app’s backend, including data storage, user authentication, static hosting, and more. With Firebase, you can easily build mobile and web apps that scale manifolds.

Let us have a glimpse of Firebase 🔥, and all the tools and services that it provides :

  • :: Build Better Apps — Firebase lets you build more powerful, secure and scalable apps with the help of firebase functionalities like Cloud Firestore , ML Kit , Cloud Functions, Hosting , Authentication , Cloud Storage , Real Time Database enhancing the app quality and monitor performance .
  • :: Improve App Quality — Firebase gives you insights into app performance and stability, so you can channel your resources effectively using functionalities like Crashlytics , Performance Monitoring , Test Labs .
  • :: Grow Your Business — Firebase helps you grow to millions of users, simplifying user engagement and retention using it’s functionalities like :
  • In-App Messaging , Google Analytics , A/B Testing , Predictions , Cloud Messaging(FCM) , Remote Configuration , Dynamic Links , App Indexing

As Flutter can be readily used to develop applications for multiple platforms, Firebase products work significantly great by sharing Data and Insights so that they can work profoundly better together.

For more information about Firebase, please visit the official Firebase website.

Firebase Showcase :

Click to know more about Firebase

Intro to the Topic : Firebase Crashlytics 🚀

Firebase Crashlytics — Firebase Crashlytics is a lightweight, realtime crash reporter that helps you track, prioritize, and fix stability issues that erode your app quality.

The Most Powerful, yet Lightest Weight Crash Reporting Solution

Crashlytics helps using 3 main aspects :

  • Logs: Each events in app is logged so that conext can be provided alongwith crash reports on the event of app crash
  • Crash reports: Crash reports is made up each time a crash occurs and sent up on the application being run the next time .
  • Stack traces: If the app recovers from an error , Dart Stack trace help in still Reporting the error.

If you wish to learn more about Firebase Crashlytics, You can check out the following video made by firebase :

Firebase Crashlytics : Key Capabilities

Crashlytics Key Capabilities
  • :: Curated Crash Reports — Firebase Crashlytics amalgamate an avalanche of crashes Into a well curated & identifiable list of issues providing contextual informaion highlighting the seriousness & pervasiveness of crashes so that you can easily pinpoint the root crash cause .
  • :: Cures for Common Crash — Crashlytics provides Crash Insights highlighting the common stability problems . Also providing great resources that make them easier to troubleshoot — Priortize & Resolve .
  • :: Analytics Inegraion — Crashlytics alongwith Analytics provide Audience Insights with Crash Analytics report for users & Simplify debugging by giving you access a list of other events leading up to each crash .
  • :: Realtime alerts — Crashlytics will help you get realtime alerts for new issues, regressed issues, and growing issues that might require immediate attention.

Implementation Pattern : Firebase Crashlytics

Let us understand the Implementation pattern of Firebase Crashlytics:-

Firebase Crashlytics saves you troubleshooting time by Intelligently Grouping Crashes and Highlighting the circumstances that lead up to them.

  • : Connect Your App — Add On Firebase To Your Apps.
  • : Integrate The SDK — Add the Crashlytics SDK
  • : Check Firebase Console — Visit the Firebase console to track, prioritize, and fix issues in your app.

Firebase Crashlytics — Setup & Initial Configuration

In order to Integrate Crashlytics, We need to create a firebase project for the Firebase Crashlytics from firebase.google.com by logging in with your Google account. This brings us to the following screen:

Add project at Firebase Console

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

Mention Name of project

Select the appropriate name for the project entering continue further

select analytics (if needed )

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

Firebase project created

This Progress indicator will show before the dashboard indicating success.

Dashboard Screen

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

Integration with iOS App

In the project overview page, select the iOS icon to launch the setup flow. If you have already added the app to your project provide click on add app to provide details of your application.

iOS app Integration
  1. Register your app with Firebase :
  2. a. Provide with your app’s bundle ID.
    Find this bundle ID from your open project in XCode. Select the top-level app in the project navigator, then access the General tab. The Bundle Identifier value is the iOS bundle ID (for example, com.yourcompany.ios-app-name).
    b. You may also provide optional details like App Nick Name and App Store ID.
    c. Register your app.

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

Download GoogleService-Info.plist

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

google-service.json
  • Open Project Settings in the Firebase console and select iOS application.
  • Now We need to add the App Store Id of the flutter application which can be located at the app’s URL.
  • We can also use makeshift app ID if our app is not published yet which can be replaced later.
  • We may need to add the Team ID which can be located at the Apple Member Centre under the provisioning profile.

Add the Firebase configuration file :

:. Click Download GoogleService-Info.plist to obtain your Firebase iOS config file (GoogleService-Info.plist).

Make sure the config file is not appended with additional characters, like (2).

:. Using XCode, move the file into the Runner/Runner directory of your Flutter app.

Adding Crashlytics plugin In Flutter App :

Add Package Dependency in pubspec.yamland the run Flutter pub get :

firebase_crashlytics: "^0.2.0"

Add the following classpath to your android/build.gradle file :

dependencies {
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.2.0'}

Apply the following Plugin to the end of your android/app/build.gradle file.

apply plugin: 'com.google.firebase.crashlytics'

Add the Firebase Crashlytics SDK, in your android/app/build.gradle files.

dependencies {
// Adding Firebase Crashlytics SDK
implementation 'com.google.firebase:firebase-crashlytics:17.0.0-beta01'
}

iOS :

: Select Runner at project navigation from Xcode .

: Then Select the Tab Build phase => Click on + > New Run Script Phase

: Add ${PODS_ROOT}/FirebaseCrashlytics/run to the Type a script.. text box.

Import package At Your Project File:

import 'package:firebase_crashlytics/firebase_crashlytics.dart';

Add Firebase Crashlytics Instance In Your Flutter App :

void main() {
// Set `enableInDevMode`to true to see reports while in debug mode
// This is only to be used for confirming that reports are being
// submitted as expected. It is not intended to be used for //everyday development.
  Crashlytics.instance.enableInDevMode = true;

// Pass all uncaught errors to Crashlytics.
FlutterError.onError = Crashlytics.instance.recordFlutterError;
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]).then((_) {
SharedPreferences.getInstance().then((prefs) {
var darkModeOn = prefs.getBool('darkMode') ?? true;
runZoned(() {
runApp(ChangeNotifierProvider<ThemeNotifier>(
create: (_) => ThemeNotifier(darkModeOn ? darkTheme : lightTheme),
child: MyApp(),
));
}, onError: Crashlytics.instance.recordError);
});
});
}

Rebuild your app :

$ flutter run

You will be abled to see the crashlytics dashboard in firebase console on successful installation

Crashlytics Console

Closing Thoughts

We have familiarised ourselves with Firebase Crashlytics — Integration in apps. They can be embodied as a tool that can play an Influential role in Strengthening Up of Apps By Availing Curated Crash Reports, Curing Common Crashes, Getting Realtime Updates to Prioritize Bug Fixing & It’s Integration with Analytics to Contemplate Future Campaign Strategies. Hope After reading the article you must have gotten insightful of Firebase Crashlytics in Flutter. Give it a TRY!!


To find out more about Firebase Crashlytics :

Check out the documentation here and Give them a Try — A link away.

References For the Blog :

firebase_crashlytics | Flutter Package
A Flutter plugin to use the Firebase Crashlytics Service. For Flutter plugins for other Firebase products, see…pub.dev

Flutter – Beautiful native apps in record time
Flutter is Google’s UI toolkit for crafting beautiful, natively compiled applications for mobile, web, and desktop from…flutter.dev

Firebase
Firebase gives you functionality like analytics, databases, messaging and crash reporting so you can move quickly and…firebase.google.com

Crashlytics | FlutterFire
Crashlytics helps you to collect analytics and details about crashes and errors that occur in your app. It does this…firebase.flutter.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.

Custom AppBar in Flutter

0

Flutter is an amazing UI tool kit used to make beautiful apps using a single codebase for android and ios. Using flutter we can build highly Animated widgets with ease. Flutter allows us to deliver Interactive applications that allow the developer to grab User Retention.

In this, we shall learn about how to build an animated AppBar. Building this AppBar will help you to learn and explore new widgets.


What we will build?

Build Up an Animated Appbar that will change its color on scrolling in any direction. Particularly, App bar items: drawer icon, action widget, and title text will change color to white in scroll direction downward and blue in upward scroll to its original formal color.

Demo of Module :

AppBar Demo Module *gif*

Table of content

:: Notification Listener

::AnimatedBulder

::Animation

:: Create the Custom AppBar


                     *** NotificationListener ***                         
  • NotificationListerner is a widget that listens to the notification and it will start bubbling that notification at the given buildContext.
  • This notification will be delivered to all the ancestors widgets that need to be changed on any effect or event eg. Scrolling of the given BuildContext.
  • It takes a onNotification property, it is a function that handles the callBacks.

Initializing NotificationListener

scrollListener

It a bool function that returns a bool value. Here if the ScrollNotication axis is vertical then only scroll will be true.


AnimatedBuilder

  • AnimatedBuilder is a widget that is used to create animated widgets eg. rotating Image, changing colors of widgets, etc…
  • It takes Animation and a Builder. The builder builds the animated widget and Animation creates the animation effects.
  • We must initialize the AnimationController inside the initState of the stateful widget.

You can read out the offical example of AnimatedBuilder for better understanding :

AnimatedBuilder class
A general-purpose widget for building animations. AnimatedBuilder is useful for more complex widgets that wish to…api.flutter.dev


       *** Animation ***

Introduction to Animation in Flutter
Let’s learn how to animate flutter widgets…medium.com

Creating the AppBar :

Initializing Animation and AnimationController

As you can see in the AppBar there are five widgets that are changing their colors while AppBar animation i.e. AppBar, Drawer Icon, Action Icon, Hello Text, UserName Text. So for these widgets, we will need 5 Animation :

Animation _colorTween, _homeTween, _workOutTween, _iconTween, _drawerTween;

This Animation objects will control the change of the colors of the above widgets. Also, we will be needing the AnimationController :

AnimationController _ColorAnimationController;
AnimationController _TextAnimationController;

To Learn Up Animation Basics like tween go through the Blog Introduction to Animation in Flutter.

We have to initialize the AnimationController, ColorTween inside the initState method.

@override
void initState() {
_ColorAnimationController =
AnimationController(vsync: this, duration: Duration(seconds: 0));
_colorTween = ColorTween(begin: Colors.transparent, end: Colors.white)
.animate(_ColorAnimationController);
_iconTween =
ColorTween(begin: Colors.white, end: Colors.lightBlue.withOpacity(0.5))
.animate(_ColorAnimationController);
_drawerTween = ColorTween(begin: Colors.white, end: Colors.black)
.animate(_ColorAnimationController);
_homeTween = ColorTween(begin: Colors.white, end: Colors.blue)
.animate(_ColorAnimationController);
_workOutTween = ColorTween(begin: Colors.white, end: Colors.black)
.animate(_ColorAnimationController);
_TextAnimationController =
AnimationController(vsync: this, duration: Duration(seconds: 0));

super.initState();
}

This code is about initializing all the objects that we have created earlier. You can also add the animations effects curves.

TIP:: You should always initialize the AnimationController, ColorTween, Tween inside the initState method……..💡💡

CustomAppBar using the AnimaionBuilder .

You might be aware of how to code an AppBar in Flutter. But this approach is different, as we will use AnimationBuilder and Stack widget to make this type of custom AppBar. Here AnimaionBuilder will return an AppBar that we will use in the Stack inside the main Scaffold .

I have made a separate widget for AppBar to keep our code clear and easy to understand and manage.

https://gist.github.com/anmolseth06/8a3b32424a7572ad3764301b9bb533be#file-customappbar-dart

Here I have used a Container height 80, and the child of that Container is a AnimationBuilder that builds the AppBar. Also, we will change the icon of the Drawer because if we use the default Drawer then neither you can change the color of the icon nor the icon of the Drawer. To open that Drawer on taping that icon can be achieved through GlobalKey . Also, I have used Function onPressed to pass the function that will open the Drawer.

NOTE : GlobalKey must be initialized inside the main file where you will use this Custom AppBar…📝

Creating a GlobalKey object

final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();

This is how you will initialize the AnimatedAppBar widget.

AnimatedAppBar(
drawerTween: _drawerTween,
onPressed: () {
scaffoldKey.currentState.openDrawer();
},
colorAnimationController: _ColorAnimationController,
colorTween: _colorTween,
homeTween: _homeTween,
iconTween: _iconTween,
workOutTween: _workOutTween,
)

NOTE : Don’t forget to add this line inside the main Scaffold ::drawer: Drawer(), 📝

https://gist.github.com/anmolseth06/c099384aac15b640cd1560a8a68ec463#file-landingpage-dart

Now you are ready to go to implement animation into your apps. Thanks…

VIDEO REFERENCES :


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


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

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.

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

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.

Using ML Kit in Flutter

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

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

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.

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

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.