Google search engine
Home Blog Page 46

Custom Progress Indicator In Flutter

In this article, we will explore the Custom Progress Indicator in a flutter Using the liquid progress indicator package. With the help of the package, we can easily achieve flutter animated liquid wave progress indicators.

We will implement a demo of the Custom Progress Indicator that can be easily embedded in your flutter applications.


Table Of Contents :

Custom Progress Indicator

Implementation

Code Implement

Code File

Conclusion


Custom Progress Indicator :

A Custom liquid progress indicator is what we’ll actually use to draw our animated liquid wave progress bar. Liquid Custom Progress Indicator sub-classes need to implement the liquid progress bar Custom Progress Indicator .with the help of custom indicator, we can give custom shape to our progress bar.

Demo Module :

Implementation :

Step 1: Add dependencies.

Add dependencies to pubspec — yaml file.

dependencies:
liquid_progress_indicator: ^0.3.2

Step 2: import the package :

import 'package:liquid_progress_indicator/liquid_progress_indicator.dart';

Step 3: Run flutter package get

Code Implement :

Create a new dart file is called custom_progress_indicator.dart inside the lib folder

In this screen,First of all,We have set the percentage timer in the init state which will increase the timer when the progress bar in running them in your Application.

@override
void initState() {
Timer timer;
timer = Timer.periodic(Duration(milliseconds:300),(_){
print('Percent Update');
setState(() {
percent+=1;
if(percent >= 100){
timer.cancel();
// percent=0;
}
});
});
super.initState();
}

Now we will initialize the LiquidCircularProgressIndicator which is a progress bar show in liquid form.

LiquidCircularProgressIndicator(
value:percent/100, // Defaults to 0.5.
valueColor: AlwaysStoppedAnimation(Colors.pink),
backgroundColor: Colors.white,
borderColor: Colors.red,
borderWidth:4.0,
direction: Axis.vertical,
center:Text(percent.toString() +"%",style: TextStyle(fontSize:12.0,fontWeight: FontWeight.w600,color: Colors.black),),
),

Now we will initialize the LiquidLinearProgressIndicator which is a progress bar show in liquid form.

LiquidLinearProgressIndicator(
value:percent/100,
valueColor: AlwaysStoppedAnimation(Colors.pink),
backgroundColor: Colors.white,
borderColor: Colors.red,
borderWidth: 5.0,
borderRadius: 12.0,
direction: Axis.horizontal,
center:Text(percent.toString() +"%",style: TextStyle(fontSize:12.0,fontWeight: FontWeight.w600,color: Colors.black),),

),

Creating Our Custom Shaped Indicator :

LiquidCustomProgressIndicator(
value:percent/100,
valueColor: AlwaysStoppedAnimation(Colors.cyan),
backgroundColor: Colors.grey[100],
Colors.black),),
direction: Axis.vertical,
shapePath:_buildBoatPath(),
),

Code File :

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:liquid_progress_indicator/liquid_progress_indicator.dart';
import 'dart:math' as math;

class CustomProgressIndicator extends StatefulWidget {
@override
_CustomProgressIndicatorState createState() =>
_CustomProgressIndicatorState();
}

class _CustomProgressIndicatorState extends State<CustomProgressIndicator> {
double _height;
double _width;

double percent = 0.0;

@override
void initState() {
Timer timer;
timer = Timer.periodic(Duration(milliseconds: 300), (_) {
print('Percent Update');
setState(() {
percent += 1;
if (percent >= 100) {
timer.cancel();
// percent=0;
}
});
});
super.initState();
}

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;

return Scaffold(
appBar: AppBar(
title: Text(
"Liquid Progress Bar",
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white,
centerTitle: true,
),
body: Container(
height: _height,
width: _width,
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
Text(
'Liquid Circular Progress Indicator',
style: TextStyle(
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w700,
fontSize: 15),
),
SizedBox(
height: 40,
),
Container(
height: 130,
width: 130,
child: LiquidCircularProgressIndicator(
value: percent / 100,
// Defaults to 0.5.
valueColor: AlwaysStoppedAnimation(Colors.pink),
backgroundColor: Colors.white,
borderColor: Colors.red,
borderWidth: 4.0,
direction: Axis.vertical,
center: Text(
percent.toString() + "%",
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w600,
color: Colors.black),
),
),
),
],
),
Column(
children: [
Text(
'Liquid linear progress indicator',
style: TextStyle(
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w700,
fontSize: 15),
),
SizedBox(
height: 40,
),
Container(
height: 40,
child: LiquidLinearProgressIndicator(
value: percent / 100,
valueColor: AlwaysStoppedAnimation(Colors.pink),
backgroundColor: Colors.white,
borderColor: Colors.red,
borderWidth: 5.0,
borderRadius: 12.0,
direction: Axis.horizontal,
center: Text(
percent.toString() + "%",
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w600,
color: Colors.black),
),
),
),
],
),
Column(
children: [
Text(
'Liquid custom progress indicator.',
style: TextStyle(
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w700,
fontSize: 15),
),
Container(
child: LiquidCustomProgressIndicator(
value: percent / 100,
valueColor: AlwaysStoppedAnimation(Colors.cyan),
backgroundColor: Colors.grey[100],
direction: Axis.vertical,
shapePath: _buildBoatPath(),
),
),
],
),
],
),
),
);
}

Path _buildBoatPath() {
return Path()
..moveTo(15, 120)
..lineTo(0, 85)
..lineTo(50, 85)
..lineTo(60, 80)
..lineTo(60, 85)
..lineTo(120, 85)
..lineTo(105, 120) //and back to the origin, could not be necessary #1
..close();
}
}

Conclusion :

In this article, I have explained a Custom Progress Indicator demo, you can modify and experiment according to your own, this little introduction was from the date time picker from our side.

I hope this blog helps will provide you with sufficient information in Trying up the Custom Progress Indicator in your flutter project. In this demo explain the liquid progress bar through the liquid_progress_indicator package in a flutter. 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.

Implement Showcase In Flutter

An extraordinary application UI limits the friction between user and application usefulness. A method for decreasing that grating is to feature and showcase the parts of your application. This is useful when a user launches your application interestingly. With the assistance of the Showcase and ShowCaseWidget widget, we can showcase the feature in the Flutter application.

This article will explore the Implement Showcase In Flutter. We will see how to implement a demo program. It will show a highlight of our app using the showcaseview package in your flutter applications.

showcaseview | Flutter Package
A Flutter package allows you to Showcase/Highlight your widgets step by step. Add dependency to pubspec.yaml Get the…pub.dev


Table Of Contents::

Introduction

Constructor

Parameters

Implementation

Code Implement

Code File

Conclusion



Introduction:

The showcase will feature the fundamental features of our application. At the point when the user taps on the screen, the widgets we have as a component of the feature will be introduced in a predefined request.

Demo Module::

This demo video shows how to implement the Showcase in a flutter and shows how a Showcase will work using the showcaseview package in your flutter applications. We will show a user press on the screen, then the showcase will be presented and When you run the app, the showcase will start instantly on the main page. It will be shown on your device.

Constructor:

To utilize Showcase, you need to call the constructor underneath:

const Showcase({
required this.key,
required this.child,
this.title,
required this.description,
this.shapeBorder,
this.overlayColor = Colors.black45,
this.overlayOpacity = 0.75,
this.titleTextStyle,
this.descTextStyle,
this.showcaseBackgroundColor = Colors.white,
this.textColor = Colors.black,
this.scrollLoadingWidget = const CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.white)),
this.showArrow = true,
this.onTargetClick,
this.disposeOnTap,
this.animationDuration = const Duration(milliseconds: 2000),
this.disableAnimation,
this.contentPadding =
const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
this.onToolTipClick,
this.overlayPadding = EdgeInsets.zero,
this.blurValue,
this.radius,
this.onTargetLongPress,
this.onTargetDoubleTap,
})

All fields marked with @required must not be empty in the above Constructor.

Parameters:

There are some parameters of Showcase are:

  • > key: This parameter is used to unique GlobalKey to identify features showcased.
  • > child: This parameter is used to the widget can only have one child. To layout multiple children, let this widget’s child be a widget such as Row, Column, or Stack, which have a children property, and then provide the children with that widget.
  • > description: This parameter displays a string about the showcased feature.
  • > animationDuration: This parameter is used for the duration over which to animate the parameters of this container. It represents a difference from one point in time to another.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
showcaseview: ^1.1.6

Step 2: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

Step 3: Import

import 'package:showcaseview/showcaseview.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

Before we implement the showcase for individual widgets, we want to wrap our page that will show the showcase with a ShowCaseWidget. We should set the required builder parameter, which will contain the Builder widget returning our ShowcaseDemo.

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ShowCase Demo',
debugShowCheckedModeBanner: false,
home: Scaffold(
body: ShowCaseWidget(
builder: Builder(builder: (context) => const ShowcaseDemo()),
),
),
);
}

Presently, we will make a ShowcaseDemo class in the main. dart file. The ShowCaseWidget to know which widgets we need to be showcased, we want to make a key for all of those widgets. In our application, there are five widgets we need to bring to the consideration of our users when they arrive at the ShowcaseDemo.

final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final GlobalKey _first = GlobalKey();
final GlobalKey _second = GlobalKey();
final GlobalKey _third = GlobalKey();
final GlobalKey _fourth = GlobalKey();
final GlobalKey _fifth = GlobalKey();

For the showcase to begin on page construct, we should call the startShowCase the strategy within the initState of the ShowcaseDemo.

Note, notwithstanding, that calling this technique simply the manner in which we did in the button would deliver an error. To keep this from occurring, we really want to put this strategy call inside a callback function and give it to WidgetsBinding.instance!.addPostFrameCallback(). This will guarantee that everything is executed accurately during the build.

Presently, if you run the application, our delightful showcase will begin when the page builds. Tap through it until the showcase is done.

@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) => ShowCaseWidget.of(context)
.startShowCase([_first, _second, _third, _fourth, _fifth]),
);
}

In the build method, we will return Scaffold. We will add _scaffoldKey

@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
......
)}

First Showcase will be added on AppBar. We will add a key, description, and its child. Its child, we will add IconButton. In this button, we will add onPressed and icon.

leading: Showcase(
key: _first,
description: 'Press here to open drawer',
child: IconButton(
onPressed: () {
_scaffoldKey.currentState!.openDrawer();
},
icon: const Icon(Icons.menu),
),
),

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

First Showcase Output

Then, Second Showcase we will add an app bar title with the key, description, and child. In a child, we will add the text “Flutter Showcase Demo”. In a description, we will add the string “This is a demo app title”.

title: Showcase(
key: _second,
description: 'This is a demo app title',
child: const Text('Flutter Showcase Demo')),

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

Second Showcase Output

Now, we will add a third Showcase on an action widget. In this widget, We will add a key was _third, the description was “Press to see notification” and, child.

actions: [
Showcase(
key: _third,
description: 'Press to see notification',
child: IconButton(
onPressed: () {},
icon: const Icon(Icons.notifications_active)))
],

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

Third Showcase Output

Next, we will add a fourth Showcase on a body part. In the body, we will add the Column widget. In this widget, we will add crossAxisAlignment and mainAxisAlignment as the center. Its child, we will add the Showcase method. In this method, we will add key was _fourth, the description was “FlutterDevs specializes in creating cost-effective and efficient applications”, and child. In a child, new will add an image.

Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Showcase(
key: _fourth,
description:
'FlutterDevs specializes in creating cost-effective and efficient applications',
child: Image.asset(
"assets/logo.png",
height: 400,
width: 350,
)),
),
],
),

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

Fourth Showcase Output

We will create a floatingActionButton equal to the Showcase widget. In this widget, we will add a key that was _fifth, the title was “Add Image’”, the description was “Click here to add new Image”.

floatingActionButton: Showcase(
key: _fifth,
title: 'Add Image',
description: 'Click here to add new Image',
shapeBorder: const CircleBorder(),
child: FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: () {},
child: const Icon(
Icons.image,
),
),
),

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

Fifth Showcase Output

Code File:

import 'package:flutter/material.dart';
import 'package:showcaseview/showcaseview.dart';

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

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ShowCase Demo',
debugShowCheckedModeBanner: false,
home: Scaffold(
body: ShowCaseWidget(
builder: Builder(builder: (context) => const ShowcaseDemo()),
),
),
);
}
}

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

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

class _ShowcaseDemoState extends State<ShowcaseDemo> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final GlobalKey _first = GlobalKey();
final GlobalKey _second = GlobalKey();
final GlobalKey _third = GlobalKey();
final GlobalKey _fourth = GlobalKey();
final GlobalKey _fifth = GlobalKey();

@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) => ShowCaseWidget.of(context)
.startShowCase([_first, _second, _third, _fourth, _fifth]),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: const <Widget>[
DrawerHeader(
decoration: BoxDecoration(
color: Colors.cyan,
),
child: Text(
'Drawer Header',
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
),
ListTile(
leading: Icon(Icons.account_circle),
title: Text('Profile'),
),
ListTile(
leading: Icon(Icons.settings),
title: Text('Settings'),
),
],
),
),
appBar: AppBar(
leading: Showcase(
key: _first,
description: 'Press here to open drawer',
child: IconButton(
onPressed: () {
_scaffoldKey.currentState!.openDrawer();
},
icon: const Icon(Icons.menu),
),
),
actions: [
Showcase(
key: _third,
description: 'Press to see notification',
child: IconButton(
onPressed: () {},
icon: const Icon(Icons.notifications_active)))
],
title: Showcase(
key: _second,
description: 'This is a demo app title',
child: const Text('Flutter Showcase Demo')),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.cyan,
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Showcase(
key: _fourth,
description:
'FlutterDevs specializes in creating cost-effective and efficient applications',
child: Image.asset(
"assets/logo.png",
height: 400,
width: 350,
)),
),
],
),
floatingActionButton: Showcase(
key: _fifth,
title: 'Add Image',
description: 'Click here to add new Image',
shapeBorder: const CircleBorder(),
child: FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: () {},
child: const Icon(
Icons.image,
),
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Implementing Showcase in your flutter projectsWe will show you what the Introduction is. Make a demo program for working Showcase using the showcaseview package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

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.


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.