Google search engine
Home Blog Page 29

Draggable Floating Action Button In Flutter

0

Flutter permits you to add a floating action button utilizing the FloatingActionButton widget. Nonetheless, it doesn’t permit you to drag the button. Consider the possibility that you need to make it draggable. This article has a model that discloses what you need to do to make a floating action button that can be hauled anyplace around the screen as long as it’s inside the parent widget.

In this blog, we will explore the Draggable Floating Action Button In Flutter. We will see how to implement a demo program of the draggable floating action button and show how to create it in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create a draggable floating action button in a flutter. It shows how the draggable floating action button will work in your flutter applications. It shows when the code successfully runs, then the user dragged a floating action button anywhere around the screen as long as it’s within the parent widget. It will be shown on your devices.

Demo Module :

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.

First, we will create a Globalkey and name it called _parentKey

final GlobalKey _parentKey = GlobalKey();

In the body, we will add a Container widget with height and width. It’s child property, we will add the Stack widget. In this widget, we will add a key, text, and a DraggableFloatingActionButton(). Inside the button, we will add a container with height and width. Add image on its child property. Also, we will add initialOffset, parent key, and onPressed. We will deeply define the below code.

Container(
width: 300,
height: 300,
child: Stack(
key: _parentKey,
children: [
Container(color: Colors.cyan),
Center(
child: const Text(
"FlutterDev's.com",
style: const TextStyle(color: Colors.white, fontSize: 24),
),
),
DraggableFloatingActionButton(
child: Container(
width: 60,
height: 60,
decoration: ShapeDecoration(
shape: CircleBorder(),
color: Colors.white,
),
child: Image.asset("assets/logo.png"),
),
initialOffset: const Offset(120, 70),
parentKey: _parentKey,
onPressed: () {},
),
],
),
)

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

We will make a class for such a widget. The main thing we need to deal with is the capacity to make the button draggable after the pointer. One of the widgets that can be utilized is Listener, which can identify pointer move events and give the movement detail. Essentially, the button should be wrapped as the child of a Listener.

The Listener widget has onPointerMove the contention which can be utilized to pass a callback that will be considered when the pointer is moving. The callback function should have a boundary PointerMoveEvent that contains the development delta in x and y headings (delta. dx and delta. dy). The offset of the catch should be refreshed by the movement delta.

The following is the class for making draggable floating action buttons. It has a few contentions which incorporate child, initialOffset, and onPressed. The child widget is delivered utilizing Positioned the widget dependent on the current offset. It’s additionally wrapped as the child of a Listener widget. There’s additionally a strategy _updatePosition that refreshes the current offset dependent on the movement delta.

class DraggableFloatingActionButton extends StatefulWidget {

final Widget child;
final Offset initialOffset;
final VoidCallback onPressed;

DraggableFloatingActionButton({
required this.child,
required this.initialOffset,
required this.onPressed,
});

@override
State<StatefulWidget> createState() => _DraggableFloatingActionButtonState();
}

class _DraggableFloatingActionButtonState extends State<DraggableFloatingActionButton> {

bool _isDragging = false;
late Offset _offset;

@override
void initState() {
super.initState();
_offset = widget.initialOffset;
}

void _updatePosition(PointerMoveEvent pointerMoveEvent) {
double newOffsetX = _offset.dx + pointerMoveEvent.delta.dx;
double newOffsetY = _offset.dy + pointerMoveEvent.delta.dy;

setState(() {
_offset = Offset(newOffsetX, newOffsetY);
});
}

@override
Widget build(BuildContext context) {
return Positioned(
left: _offset.dx,
top: _offset.dy,
child: Listener(
onPointerMove: (PointerMoveEvent pointerMoveEvent) {
_updatePosition(pointerMoveEvent);

setState(() {
_isDragging = true;
});
},
onPointerUp: (PointerUpEvent pointerUpEvent) {
print('onPointerUp');

if (_isDragging) {
setState(() {
_isDragging = false;
});
} else {
widget.onPressed();
}
},
child: widget.child,
),
);
}
}

You need to add a key to the parent widget and pass it to the DraggableFloatingActionButton widget. From the key, you can get the RenderBox from the currentContext property, which has findRenderObject a strategy. Then, at that point, you can get the size of the parent from the size property of the RenderBox. You should be cautious because the findRenderObject technique should be called after the tree is built. Subsequently, you need to summon it utilizing addPostFrameCallback of WidgetsBinding.

The _updatePosition the technique should be changed as well. On the off chance that the new offset is lower than the minimum offset, the value must be set to the minimum offset. On the off chance that the new offset is more noteworthy than the maximum offset, the value must be set to the most maximum offset. You need to do that for both x and y axes.

class DraggableFloatingActionButton extends StatefulWidget {

final Widget child;
final Offset initialOffset;
final VoidCallback onPressed;

DraggableFloatingActionButton({
required this.child,
required this.initialOffset,
required this.onPressed,
});

@override
State<StatefulWidget> createState() => _DraggableFloatingActionButtonState();
}

class _DraggableFloatingActionButtonState extends State<DraggableFloatingActionButton> {

final GlobalKey _key = GlobalKey();

bool _isDragging = false;
late Offset _offset;
late Offset _minOffset;
late Offset _maxOffset;

@override
void initState() {
super.initState();
_offset = widget.initialOffset;

WidgetsBinding.instance?.addPostFrameCallback(_setBoundary);
}

void _setBoundary(_) {
final RenderBox parentRenderBox = widget.parentKey.currentContext?.findRenderObject() as RenderBox;
final RenderBox renderBox = _key.currentContext?.findRenderObject() as RenderBox;

try {
final Size parentSize = parentRenderBox.size;
final Size size = renderBox.size;

setState(() {
_minOffset = const Offset(0, 0);
_maxOffset = Offset(
parentSize.width - size.width,
parentSize.height - size.height
);
});
} catch (e) {
print('catch: $e');
}
}

void _updatePosition(PointerMoveEvent pointerMoveEvent) {
double newOffsetX = _offset.dx + pointerMoveEvent.delta.dx;
double newOffsetY = _offset.dy + pointerMoveEvent.delta.dy;

if (newOffsetX < _minOffset.dx) {
newOffsetX = _minOffset.dx;
} else if (newOffsetX > _maxOffset.dx) {
newOffsetX = _maxOffset.dx;
}

if (newOffsetY < _minOffset.dy) {
newOffsetY = _minOffset.dy;
} else if (newOffsetY > _maxOffset.dy) {
newOffsetY = _maxOffset.dy;
}

setState(() {
_offset = Offset(newOffsetX, newOffsetY);
});
}

@override
Widget build(BuildContext context) {
return Positioned(
left: _offset.dx,
top: _offset.dy,
child: Listener(
onPointerMove: (PointerMoveEvent pointerMoveEvent) {
_updatePosition(pointerMoveEvent);

setState(() {
_isDragging = true;
});
},
onPointerUp: (PointerUpEvent pointerUpEvent) {
print('onPointerUp');

if (_isDragging) {
setState(() {
_isDragging = false;
});
} else {
widget.onPressed();
}
},
child: Container(
key: _key,
child: widget.child,
),
),
);
}
}

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

Final Output

Code File:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_draggable_floating/draggable_floating_action_button.dart';
import 'package:flutter_draggable_floating/splash_screen.dart';

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

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class DraggableFloatingActionButtonDemo extends StatelessWidget {

final GlobalKey _parentKey = GlobalKey();

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Flutter Draggable Floating Action Button'),
backgroundColor: Colors.cyan,
),
body: Column(
children: [
Container(
height: 150,
),
Container(
width: 300,
height: 300,
child: Stack(
key: _parentKey,
children: [
Container(color: Colors.cyan),
Center(
child: const Text(
"FlutterDev's.com",
style: const TextStyle(color: Colors.white, fontSize: 24),
),
),
DraggableFloatingActionButton(
child: Container(
width: 60,
height: 60,
decoration: ShapeDecoration(
shape: CircleBorder(),
color: Colors.white,
),
child: Image.asset("assets/logo.png"),
),
initialOffset: const Offset(120, 70),
parentKey: _parentKey,
onPressed: () {},
),
],
),
)
],
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Draggable Floating Action Button in your flutter projectsWe will show you what the Introduction is?. That is the way to make a draggable floating action button in Flutter. Fundamentally, you can utilize Listener the widget to distinguish pointer move events and update the button offset dependent on the development delta. The Listener widget likewise upholds distinguishing pointer-up events at which the button’s activity ought to be performed except if it has recently been dragged. You likewise need to get the size of the parent and the button to keep the button from being out of the parent’s box. 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 a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

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


Explore Open URLs In Flutter

0

While surfing the net, each user will go over numerous buttons, text, and so forth, that would divert the user to an alternate website page in a similar tab or an alternate tab when clicked. Now and then, we might need to divert users to explicit links or websites by inciting a browser.

In this article, we will Explore Open URLs In Flutter. We will implement a demo program of the URL and how to open URLs in browser and app using the url_launcher package in your flutter applications.

url_launcher | Flutter Package
A Flutter plugin for launching a URL. Supports iOS, Android, web, Windows, macOS, and Linux. To use this plugin, add…pub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

In Flutter, everything is a widget and similarly, Flutter likewise utilizes a lot of plugins or dependencies to make the application work quicker and simpler. For this situation, the “url_launcher” plugin can be utilized to dispatch the URL in a mobile application.

Similarly, when a developer interfaces a URL to a button or text in an application, the application will open the website when clicked in the accompanying manners:

  • In browser(default)
  • In-App

With regards to opening a website in a browser then it includes two applications at work. One of the applications that the user is utilizing and the other is the browser. Yet, with regards to, in-application opening, it includes only one application. Every one of these highlights can be utilized by a developer as indicated by the need of the user.

Demo Module :

This demo video shows how to open a url’s in a flutter. It shows how the URLs will work using the url_launcher package in your flutter applications. It shows open URLs in the external browser and In-app. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

url_launcher:

Step 2: Import

import 'package:url_launcher/url_launcher.dart';

Step 3: 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.

Presently, how about we make a function that can be called at whatever point the user clicks a button that is connected to a URL, to open it in a browser.

_launchURLBrowser() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

The function is named here as “_launchURLBrowser” and the function is proclaimed as “async” so it returns a guarantee. The “url” variable is allowed with the necessary web address, as a string. It is pronounced as a “const” with the goal that the variable isn’t changed in any situation. On the off chance that there is the possibility to dispatch the URL, just the url is launch by calling the launch() work with url variable as a trait. Else, it will throw/print a text with the URLs value, as a blunder message.

Presently, how about we make a function that can be called at whatever point the user clicks a button that is connected to a URL, to open it in a app.

_launchURLApp() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url, forceSafariVC: true, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}

The function is named here as “_launchURLApp” and the function is proclaimed as “async” so it returns a guarantee. The “url” variable is doled out with the necessary web address, as a string. It is pronounced as a “const” so the variable isn’t changed at any condition. On the off chance that there is plausible to dispatch the URL, just the url is launched by calling the launch() function with url variable as a property. Else, it will throw/print a text with the url value, as an error message.

To open the URL inside the application, two conditions must be made valid.

  • > forceWebView: true — this helps the app start the app’s web view for the website to open inside the app itself.
  • > forceSafariVC: true — in iOS devices, this helps the app to open the website in the Safari View Controller other than the default browser.

Note: In browser opening, the forceWebView and forceSafariVC are set to “false” by default.

The above functions can be called whenever needed in code, by calling the name of the functions as such. In the body, we will create two raised buttons having the text “Press Url Browser” and “Press Url App” on it, respectively.

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLBrowser,
child: Text('Press Url Browser',style: TextStyle(color: Colors.white),),
),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLApp,
padding: EdgeInsets.only(left: 30,right: 30),
child: Text('Press Url App',style: TextStyle(color: Colors.white),),
),
],
),

For the onPressed attribute, we are calling _launchURLBrowser and _launchURLApp individually so that, when the first button is pressed the URL is opened in a browser, and when the second button is pressed the URL is opened in the actual application. When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_url/splash_screen.dart';
import 'package:url_launcher/url_launcher.dart';

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

class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class OpenUrlDemo extends StatelessWidget {

_launchURLBrowser() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

_launchURLApp() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url, forceSafariVC: true, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}


@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.black,
title: Text('Flutter Open Url Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLBrowser,
child: Text('Press Url Browser',style: TextStyle(color: Colors.white),),
),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
color: Colors.teal,
onPressed: _launchURLApp,
padding: EdgeInsets.only(left: 30,right: 30),
child: Text('Press Url App',style: TextStyle(color: Colors.white),),
),
],
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Open URLs in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working Open URLs and it shows open URLs in the external browser and In-app itself using the url_launcher 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.

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

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

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Explore Exception Handling In Flutter

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


Exploring Flutter Essentials Lists

0

Flutter is an open-source structure to make the superior grade, elite mobile applications across mobile working systems — Android and iOS. It gives a basic, amazing, productive, and straightforward SDK to compose a mobile application in Google’s own language, Dart.

In this blog, we will be Exploring Flutter Essentials Lists. We will also implement a demo program and we are going to talk about lists in your flutter applications.

Table of Contents:

Using ListView how to handle lists in Flutter

Using ListTile is a useful widget for list items

The builder constructor

Separated constructor & Divider widget

How to implement a horizontal list



Using ListView how to handle lists in Flutter:

Making a list utilizing Flutter is truly simple as it accompanies an inherent widget called ListView, which handles everything for you. How about we perceive how to make a fundamental utilization of this widget.

To deliver a list, add a ListView widget. It has numerous properties, and one of these is called children, which accepts an array of widgets as value. Along these lines, a straightforward list would resemble this:

ListView (
children: <Widget>[
// ...widgets to show in the list...
],
)

> Space rules :

There are two rules you need to think about going to see how ListView chooses how much space to take on your screen.

  • The list will fill up all the width available;
  • The height of each item should be defined, implicitly, or explicitly.

There’s very little to say about the first point: except if you have a widget with a characterized width to contain your list, it will top off all the accessible space evenly. The second rule implies that when you characterize a thing of the list, the ListView ought to have the option to tell how high everything will be.

Using ListTile is a useful widget for list items:

Another valuable widget to think about is the ListTile widget. This is generally used to deliver each list item as it is adaptable enough for that utilization. It has a title, a subtitle, a leading widget, and a trailing widget, as you can find in the photos beneath.

ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey.shade300,
child: Text('Y'),
),
title: Text('THIS IS A TITLE'),
subtitle: Text('This is a subtitle and it has a different style'),
trailing: Icon(Icons.delete),
)

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

This widget is incredible assuming you need your list of components to follow the material plan details. It has two properties to enable interaction: the onTap and the onLongPress callbacks.

The builder constructor:

We’ve perceived how to implement out a list in Flutter. The technique displayed before is acceptable if you have a list with few things, however, it experiences execution issues on the off chance that you need to deal with a more extended list: this happens because it attempts to deliver everything of the list, even though they are not noticeable on the screen! You comprehend that for an extremely extensive list, it very well may be an issue.

The solution:

To tackle the referenced issue, ListView accompanies an exceptional constructor called builder, and it is savvy enough to deliver just the widgets right now apparent on the screen. A list utilizing the builder constructor resembles this:

The primary thing to see is that you will not utilize the “children” property any longer by utilizing the developer constructor. All things considered, you need to characterize the itemCount and the itemBuilder property; how about we see what they are.

itemCount and itemBuilder:

class MyList extends StatelessWidget {
final items = ["first title", "title 2", "title 3", "last title"];

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) => Text(items[index]),
);
}
}

Separated constructor & Divider widget:

We’ve effectively seen two constructors of the ListView widget. It has a third one called separated. This one is based upon the past one and adds another element: you can put some divider between your list items. There are numerous methods of partitioning your substance. For instance, a straight line might be utilized, or 3 horizontal dots, as Medium itself does. Flutter has the Divider widget that defines a horizontal line.

We should perceive what we need to utilize this constructor:

class MyList extends StatelessWidget {
final items = ["first title", "title 2", "title 3", "last title"];

@override
Widget build(BuildContext context) {
return ListView.separated(
padding: EdgeInsets.all(10),
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
leading: Icon(Icons.arrow_forward),
);
},
separatorBuilder: (context, index) {
return Divider(
thickness: 2,
);
},
);
}
}

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

separatorBuilder parameter:

The separatorBuilder works precisely as the itemBuilder. Rather than dealing with the list components, it deals with every separator: you need to pass in a capacity that takes a BuilderContext and an integer index, and it should return a widget.

It doesn’t occur much regularly to the function’s contributions to be of any need. That is because typically, the separator ought to consistently be something very similar, regardless of which things of the list you’re dividing. All things considered, if the one above isn’t the situation, you can utilize the unique context and the index to characterize which widget to return as we do with the itemBuilder parameter.

How to implement a horizontal list:

Now and again you need to swipe through your items horizontally. In Flutter, it’s clear to accomplish that!. You should simply characterize the property scrollDirection, which ought to be appointed a value from the Axis enum, and one of its values is horizontal, the one we were searching for. We should perceive how everything meets up:

class MyList extends StatelessWidget {
final items = ["first title", "title 2", "title 3", "last title"];

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Container(
width: 200,
child: Card(
elevation: 2,
child: ListTile(title: Text(items[index])),
),
),
);
}
}

You may have seen that everything has a predetermined width. That is because level records act as the specific inverse of vertical ones. The rules applied to a vertical list we’ve seen before don’t work here any longer. In this way, we should perceive what changed.

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Flutter Essentials Lists in your flutter projects. That’s all. There is plenty more Flutter has to offer regarding lists, but I wanted to lay down the most useful concepts. So please try it.

❤ ❤ Thanks for reading this 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 a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Exploring Dart DevTools

Related: Exploring Threading In Flutter

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


Explore Customizable Time Planner In Flutter

Flutter has been a great encounter from the earliest starting point. Building ravishing UI had never been speedier. It’s not difficult to become hopelessly enamored with Flutter, whether or not you’re an amateur or a cultivated developer. All software developers understand that dates are the trickiest thing. Likewise, schedules are no special case.

In mobile apps, there are many cases where a user needs to enter a date like date of birth, book a ticket, schedule a meeting, etc.

In this blog, we will Explore Customizable Time Planner In Flutter. We will also implement a demo program and create a customizable time planner using the time_planner package in your flutter applications.

time_planner | Flutter Package
A beautiful, easy to use and customizable time planner for flutter mobile 📱, desktop 🖥 and web 🌐 This is a widget…pub.dev

Table Of Contents::

Introduction

Attributes

Implementation

Code Implement

Code File

Conclusion



Introduction:

A delightful, simple to utilize, and customizable time planner for flutter mobile, desktop, and web. This is a widget to show assignments to clients on a schedule. Each row shows an hour and every column shows a day, yet you can change the title of the section and show whatever else you need.

Demo Module :

This demo video shows how to create a customizable time planner in a flutter. It shows how the customizable time planner will work using the time_planner package in your flutter applications. It shows when the user taps on any row and column then a random time planner will be created. animated. It will be shown on your device.

Attributes:

There are some attributes of the Time Planner are:

  • > startHour: These attributes are used to time start from this, it will start from 1.
  • > endHour: These attributes are used to time end at this hour, the max value is 24.
  • > headers: These attributes are used to create days from here, each day is a TimePlannerTitle. You should create at least one day.
  • > tasks: These attributes are used to List widgets on the time planner.
  • > style: These attributes are used to Style of time planner.
  • > currentTimeAnimation: These attributes are used to widget loaded scroll to the current time with animation. Default is true.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

time_planner: 

Step 2: Import

import 'package:time_planner/time_planner.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.

First, we create a list of TimePlannerTask called variable tasks.

List<TimePlannerTask> tasks = [];

We will create a _addObject() method. Inside, we will add a List of colors and add setState() function.

void _addObject(BuildContext context) {
List<Color?> colors = [
Colors.purple,
Colors.blue,
Colors.green,
Colors.orange,
Colors.cyan
];

setState(() {
tasks.add(
TimePlannerTask(
color: colors[Random().nextInt(colors.length)],
dateTime: TimePlannerDateTime(
day: Random().nextInt(10),
hour: Random().nextInt(14) + 6,
minutes: Random().nextInt(60)),
minutesDuration: Random().nextInt(90) + 30,
daysDuration: Random().nextInt(4) + 1,
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('You click on time planner object')));
},
child: Text(
'this is a demo',
style: TextStyle(color: Colors.grey[350], fontSize: 12),
),
),
);
});

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Random task added to time planner!')));
}

In the function, we will add tasks.add()method. Inside, we will add TimePlannerTask() widget. In this widget, we will add color, date time, minutesDuration and daysDuration. We will also show snackBar messages when users tap on the time planner.

In the body, we will add TimePlanner() widget. Inside, we will add startHour, endHour, and headers. In headers, we will add some TimePlannerTitle(). Also, we will add tasks and styles.

TimePlanner(
startHour: 2,
endHour: 24,
headers: [
TimePlannerTitle(
date: "7/20/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/21/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/22/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/23/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/24/2021",
title: "saturday",
),
TimePlannerTitle(
date: "7/25/2021",
title: "sunday",
),
TimePlannerTitle(
date: "7/26/2021",
title: "monday",
),
TimePlannerTitle(
date: "7/27/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/28/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/29/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/30/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/31/2021",
title: "Saturday",
),
],
tasks: tasks,
style: TimePlannerStyle(
showScrollBar: true
),
),

Now, we will create a FloatingActionButton(). Inside, we will add onPressed, tooltip, and child.

floatingActionButton: FloatingActionButton(
onPressed: () => _addObject(context),
tooltip: 'Add random task',
child: Icon(Icons.add),
),

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

Final Output

Code File:

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_customizable_time_plan/splash_screen.dart';
import 'package:time_planner/time_planner.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: Splash()
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);

final String title;

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

class _MyHomePageState extends State<MyHomePage> {
List<TimePlannerTask> tasks = [];

void _addObject(BuildContext context) {
List<Color?> colors = [
Colors.purple,
Colors.blue,
Colors.green,
Colors.orange,
Colors.cyan
];

setState(() {
tasks.add(
TimePlannerTask(
color: colors[Random().nextInt(colors.length)],
dateTime: TimePlannerDateTime(
day: Random().nextInt(10),
hour: Random().nextInt(14) + 6,
minutes: Random().nextInt(60)),
minutesDuration: Random().nextInt(90) + 30,
daysDuration: Random().nextInt(4) + 1,
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('You click on time planner object')));
},
child: Text(
'this is a demo',
style: TextStyle(color: Colors.grey[350], fontSize: 12),
),
),
);
});

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Random task added to time planner!')));
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(widget.title),
centerTitle: true,
),
body: Center(
child: TimePlanner(
startHour: 2,
endHour: 24,
headers: [
TimePlannerTitle(
date: "7/20/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/21/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/22/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/23/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/24/2021",
title: "saturday",
),
TimePlannerTitle(
date: "7/25/2021",
title: "sunday",
),
TimePlannerTitle(
date: "7/26/2021",
title: "monday",
),
TimePlannerTitle(
date: "7/27/2021",
title: "tuesday",
),
TimePlannerTitle(
date: "7/28/2021",
title: "wednesday",
),
TimePlannerTitle(
date: "7/29/2021",
title: "thursday",
),
TimePlannerTitle(
date: "7/30/2021",
title: "friday",
),
TimePlannerTitle(
date: "7/31/2021",
title: "Saturday",
),
],
tasks: tasks,
style: TimePlannerStyle(
showScrollBar: true
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _addObject(context),
tooltip: 'Add random task',
child: Icon(Icons.add),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Customizable Time Planner in your flutter projects. We will show you what the Introduction is?, some attributes using in Time Planner, and make a demo program for working Customizable Time Planner 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.

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

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

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Related: Explore Exception Handling In Flutter

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

RepaintBoundary In Flutter

0

Flutter paints widgets to the screen. If the substance of a widget ought to be updated, it’s anything but a repaint. Notwithstanding, Flutter may likewise repaint different widgets whose content remaining parts unaltered. It can influence the application execution and at times it’s very huge. If you are searching for an approach to forestall unnecessary repaints, you can think about utilizing RepaintBoundary.

In this blog, we will explore RepaintBoundary In Flutter. We will see how to implement a demo program of the repaint boundary and how to use it in your flutter applications.

Table Of Contents::

RepaintBoundary

Why Need to Use RepaintBoundary

Code Implement

Code File

Conclusion



RepaintBoundary:

RepaintBoundary class Null safety. To start with, you need to realize what is RepaintBoundary in Flutter. It’s anything but’s a widget that makes a different presentation list for its child. As indicated by Wikipedia, a showcase list is a progression of illustrations commands that characterize an output picture. This widget makes a different presentation list for its child, Flutter proposes you use RepaintBoundary if a subtree repaints at unexpected times in comparison to its encompassing parts to further develop performance.

Why Need to Use RepaintBoundary:

Flutter widgets are related to RenderObjects. A RenderObject has a technique called paint which is utilized to perform painting. Be that as it may, the paint the method can be conjured regardless of whether the related widget occasions don’t change. That is because Flutter may perform repaint to other RenderObjects in a similar Layer if one of them is set apart as filthy. At the point when a RenderObject should be repainted utilizing RenderObject.markNeedsPaint, it advises its closest predecessor to repaint. The progenitor does likewise to its predecessor, perhaps until the root RenderObject. At the point when a RenderObject’s paint strategy is set off, the entirety of its relative RenderObjects in a similar layer will be repainted.

At times, when a RenderObject should be repainted, the other RenderObjects in a similar layer shouldn’t be repainted because their delivered substance stays unaltered. As such, it would be better if we would just repaint certain RenderObjects. Utilizing RepaintBoundary can be helpful to restrict the engendering of markNeedsPaint up the render tree and paintChild down the render tree.

RepaintBoundary can decouple the predecessor render objects from the relative render objects. In this way, it’s feasible to repaint just the subtree whose content changes. The utilization of RepaintBoundary may altogether further develop the application execution, particularly if the subtree that shouldn’t be repainted requires broad work for repainting.

How to implement code in dart file :

You need to implement it in your code respectively:

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

We will make a straightforward demo application where the background is painted utilizing CustomPainter and there are 10,000 ovals drawn. There is likewise a cursor that moves following the last position of the client touches the screen. The following is the code without RepaintBoundary.

In the body, we will create a Stack widget. Inside, we will add a StackFit.expand, and add two widgets was _buildBackground(), and _buildCursor(),. We will define the below code.

Stack(
fit: StackFit.expand,
children: <Widget>[
_buildBackground(),
_buildCursor(),
],
),

We will describe _buildBackground() widget:

In the _buildBackground() widget. We will return CustomPaint() widget. Inside, we will add BackgroundColor class on a painter. We will define below. Also, we will add is complex as true means whether to hint that this layer’s painting should be cached and willChange was false means whether the raster cache should be told that this painting is likely to change in the next frame.

Widget _buildBackground() {
return CustomPaint(
painter: BackgroundColor(MediaQuery.of(context).size),
isComplex: true,
willChange: false,
);
}

We will describe BackgroundColor class:

We will create a BackgroundColor was extend CustomPainter.

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

class BackgroundColor extends CustomPainter {

static const List<Color> colors = [
Colors.orange,
Colors.purple,
Colors.blue,
Colors.green,
Colors.purple,
Colors.red,
];

Size _size;
BackgroundColor(this._size);

@override
void paint(Canvas canvas, Size size) {
final Random rand = Random(12345);

for (int i = 0; i < 10000; i++) {
canvas.drawOval(
Rect.fromCenter(
center: Offset(
rand.nextDouble() * _size.width - 100,
rand.nextDouble() * _size.height,
),
width: rand.nextDouble() * rand.nextInt(150) + 200,
height: rand.nextDouble() * rand.nextInt(150) + 200,
),
Paint()
..color = colors[rand.nextInt(colors.length)].withOpacity(0.3)
);
}
}

@override
bool shouldRepaint(BackgroundColor other) => false;
}

We will describe _buildCursor() widget:

In this widget, we will return the Listener widget. We will add _updateOffset () widget at onPointerDown/Move and add CustomPaint widget. Inside, we will add a key and CursorPointer class. We will define below. Also, we will add ConstrainedBox().

Widget _buildCursor() {
return Listener(
onPointerDown: _updateOffset,
onPointerMove: _updateOffset,
child: CustomPaint(
key: _paintKey,
painter: CursorPointer(_offset),
child: ConstrainedBox(
constraints: BoxConstraints.expand(),
),
),
);
}

We will describe CursorPointer class:

We will create a CursorPointer was extend CustomPainter.

import 'package:flutter/material.dart';

class CursorPointer extends CustomPainter {

final Offset _offset;

CursorPointer(this._offset);

@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(
_offset,
10.0,
new Paint()..color = Colors.green,
);
}

@override
bool shouldRepaint(CursorPointer old) => old._offset != _offset;
}

When we run the application, we ought to get the screen’s output like the underneath screen video. If you try to move the pointer on the screen, the application will be so laggy because it repaints the background, requiring expensive computation.

Without Using RepaintBoundary

Presently, we will add RepaintBoundary. The answer to the above problem is wrapping the CustomPaint widget as the child of a RepaintBoundary.

Widget _buildBackground() {
return RepaintBoundary(
child: CustomPaint(
painter: BackgroundColor(MediaQuery.of(context).size),
isComplex: true,
willChange: false,
),
);
}

When we run the application, we ought to get the screen’s output like the underneath screen video. With that simple change, now the background doesn’t need to be repainted when Flutter repaints the cursor. The application should not be laggy anymore.

Using RepaintBoundary

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_repaint_boundary_demo/background_color.dart';
import 'package:flutter_repaint_boundary_demo/cursor_pointer.dart';

class HomePage extends StatefulWidget {

@override
State createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {

final GlobalKey _paintKey = new GlobalKey();
Offset _offset = Offset.zero;

Widget _buildBackground() {
return RepaintBoundary(
child: CustomPaint(
painter: BackgroundColor(MediaQuery.of(context).size),
isComplex: true,
willChange: false,
),
);
}

Widget _buildCursor() {
return Listener(
onPointerDown: _updateOffset,
onPointerMove: _updateOffset,
child: CustomPaint(
key: _paintKey,
painter: CursorPointer(_offset),
child: ConstrainedBox(
constraints: BoxConstraints.expand(),
),
),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.cyan,
title: const Text('Flutter RepaintBoundary Demo'),
),
body: Stack(
fit: StackFit.expand,
children: <Widget>[
_buildBackground(),
_buildCursor(),
],
),
);
}

_updateOffset(PointerEvent event) {
RenderBox? referenceBox = _paintKey.currentContext?.findRenderObject() as RenderBox;
Offset offset = referenceBox.globalToLocal(event.position);
setState(() {
_offset = offset;
});
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the RepaintBoundary in your flutter projectsWe will make a demo program for working Custom Chat Bubble and you should use RepaintBoundary a subtree repaint at different times than its surrounding parts. To make sure that a RepaintBounary is useful 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.

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

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

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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


Stopwatch Timer In Flutter

0

Flutter is enormously motivated by React and numerous ideas are now recognizable: stateful/stateless, render function, segment hierarchy, and so on Concerning Dart language which backs Flutter, it acquires various of the best highlights from different dialects while keeping off from the terrible things, so if you definitely know python, JavaScript, C++, you can get Dart rapidly.

In this blog, we will explore the Stopwatch Timer In Flutter. We will see how to implement a demo program of the stopwatch timer and show how to create it in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create a stopwatch timer in a flutter. It shows how the stopwatch timer will work in your flutter applications. It shows when code successfully runs, then user press the start timer button, then count down timing will be start and the user also press the stop and cancel timer button. It will be shown on your devices.

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we will create a const countdownDuration is equal to Duration was ten minutes and create a variable of duration. We will also create a timer variable and create a bool variable countDown is equal to true.

static const countdownDuration = Duration(minutes: 10);
Duration duration = Duration();
Timer? timer;

bool countDown =true;

We will create an initState() method. In this method, we will add the reset() function. We will define the below code.

@override
void initState() {
// TODO: implement initState
super.initState();
reset();
}

We will define reset() function:

We will create a reset() method. In this method, if countDown is true, then in setState() we will add duration is equal to the countdownDuration. Else, duration is equal to Duration in setState().

void reset(){
if (countDown){
setState(() =>
duration = countdownDuration);
} else{
setState(() =>
duration = Duration());
}
}

Now, we will create a startTimer() function. We will import that dart: async;

import 'dart:async';

We will add a timer variable that is equal to the Timer. periodic add duration was one second and addTime() method. We will define below the code.

void startTimer(){
timer = Timer.periodic(Duration(seconds: 1),(_) => addTime());
}

We will define addTime() method:

In the addTime method, inside we will add the final addSeconds that is equal to the countDown is true then -1 else 1. We will add setState(). Inside, final seconds that is equal to the duration.inSeconds plus addSeconds. If the second is less than zero then timer. cancel() else, the duration that is equal to the Duration(seconds: seconds).

void addTime(){
final addSeconds = countDown ? -1 : 1;
setState(() {
final seconds = duration.inSeconds + addSeconds;
if (seconds < 0){
timer?.cancel();
} else{
duration = Duration(seconds: seconds);

}
});
}

Now, we will create a stopTimer() method. In this method, if resets that are equal to true then reset() method call. We will add a timer. cancel in the setState method.

void stopTimer({bool resets = true}){
if (resets){
reset();
}
setState(() => timer?.cancel());
}

In the body, we will create Column() widget. In this widget, we will add the mainAxisAlignment was center. Add the buildTime() and buildButtons() widget. We will define below the code.

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTime(),
SizedBox(height: 80,),
buildButtons()
],
),

We will define buildTime() widget:

In this method, we will create a final hour is equal to the twoDigits(duration.inHours). Add final minutes is equal to the twoDigits(duration.inMinutes.remainder(60)). Add final seconds is equal to the twoDigits(duration.inSeconds.remainder(60)). We will return Row(). Inside, we will add three buildTimeCard() methods and we will be passing arguments time and headers. We will describe the code below.

Widget buildTime(){
String twoDigits(int n) => n.toString().padLeft(2,'0');
final hours =twoDigits(duration.inHours);
final minutes =twoDigits(duration.inMinutes.remainder(60));
final seconds =twoDigits(duration.inSeconds.remainder(60));
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTimeCard(time: hours, header:'HOURS'),
SizedBox(width: 8,),
buildTimeCard(time: minutes, header:'MINUTES'),
SizedBox(width: 8,),
buildTimeCard(time: seconds, header:'SECONDS'),
]
);
}

We will define buildTimeCard() widget:

In this widget, we will be passing two arguments was time and header. We will return Column. Inside, add a container with decoration and its child we will add text was time. We will also add another text was a header.

Widget buildTimeCard({required String time, required String header}) =>
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20)
),
child: Text(
time, style: TextStyle(fontWeight: FontWeight.bold,
color: Colors.black,fontSize: 50),),
),
SizedBox(height: 24,),
Text(header,style: TextStyle(color: Colors.black45)),
],
);

We will define buildButtons() widget:

In this widget, we will add final isRunning is equal to the timer is equal to null then false else timer .isActive. We will add final isCompleted is equal to duration.inSeconds is equal to zero. We will return isRunning || isCompleted then add a Row() widget. Inside, add ButtonWidget class. We will define the below code. Add two buttons were stop and others were canceled. Also, we will add a start timer button.

Widget buildButtons(){
final isRunning = timer == null? false: timer!.isActive;
final isCompleted = duration.inSeconds == 0;
return isRunning || isCompleted
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ButtonWidget(
text:'STOP',
onClicked: (){
if (isRunning){
stopTimer(resets: false);
}
}),
SizedBox(width: 12,),
ButtonWidget(
text: "CANCEL",
onClicked: stopTimer
),
],
)
: ButtonWidget(
text: "Start Timer!",
color: Colors.black,
backgroundColor: Colors.white,
onClicked: (){
startTimer();
});

}

We will define ButtonWidget class:

In this class, we will create an ElevatedButton(). Inside, we will add onPressed method, text.

import 'package:flutter/material.dart';

class ButtonWidget extends StatelessWidget {
final String text;
final Color color;
final Color backgroundColor;
final VoidCallback onClicked;

const ButtonWidget({Key? key, required this.text, required this.onClicked,
this.color = Colors.white, this.backgroundColor = Colors.black}) : super(key: key);
@override
Widget build(BuildContext context) => ElevatedButton(
style: ElevatedButton.styleFrom(
primary: backgroundColor,
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16)
),
onPressed: onClicked,
child: Text(text,style: TextStyle(fontSize: 20,color: color),)
);

}

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

Final Output

Code File:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_stopwatch_timer_demo/button_widget.dart';

class StopWatchTimerPage extends StatefulWidget {
@override
_StopWatchTimerPageState createState() => _StopWatchTimerPageState();
}

class _StopWatchTimerPageState extends State<StopWatchTimerPage> {
static const countdownDuration = Duration(minutes: 10);
Duration duration = Duration();
Timer? timer;

bool countDown =true;

@override
void initState() {
// TODO: implement initState
super.initState();
reset();
}

void reset(){
if (countDown){
setState(() =>
duration = countdownDuration);
} else{
setState(() =>
duration = Duration());
}
}

void startTimer(){
timer = Timer.periodic(Duration(seconds: 1),(_) => addTime());
}

void addTime(){
final addSeconds = countDown ? -1 : 1;
setState(() {
final seconds = duration.inSeconds + addSeconds;
if (seconds < 0){
timer?.cancel();
} else{
duration = Duration(seconds: seconds);

}
});
}

void stopTimer({bool resets = true}){
if (resets){
reset();
}
setState(() => timer?.cancel());
}

@override
Widget build(BuildContext context) => Scaffold(
backgroundColor: Colors.orange[50],
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text("Flutter StopWatch Timer Demo"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTime(),
SizedBox(height: 80,),
buildButtons()
],
),
),
);

Widget buildTime(){
String twoDigits(int n) => n.toString().padLeft(2,'0');
final hours =twoDigits(duration.inHours);
final minutes =twoDigits(duration.inMinutes.remainder(60));
final seconds =twoDigits(duration.inSeconds.remainder(60));
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTimeCard(time: hours, header:'HOURS'),
SizedBox(width: 8,),
buildTimeCard(time: minutes, header:'MINUTES'),
SizedBox(width: 8,),
buildTimeCard(time: seconds, header:'SECONDS'),
]
);
}

Widget buildTimeCard({required String time, required String header}) =>
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20)
),
child: Text(
time, style: TextStyle(fontWeight: FontWeight.bold,
color: Colors.black,fontSize: 50),),
),
SizedBox(height: 24,),
Text(header,style: TextStyle(color: Colors.black45)),
],
);

Widget buildButtons(){
final isRunning = timer == null? false: timer!.isActive;
final isCompleted = duration.inSeconds == 0;
return isRunning || isCompleted
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ButtonWidget(
text:'STOP',
onClicked: (){
if (isRunning){
stopTimer(resets: false);
}
}),
SizedBox(width: 12,),
ButtonWidget(
text: "CANCEL",
onClicked: stopTimer
),
],
)
: ButtonWidget(
text: "Start Timer!",
color: Colors.black,
backgroundColor: Colors.white,
onClicked: (){
startTimer();
});

}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Stopwatch Timer in your flutter projectsWe will show you what the Introduction is?. It shows when the user press the start timer button then the count down timing will be start and the user also press the stop and cancel timer button 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.

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

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

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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


Explore AnimatedSize In Flutter

0

Flutter permits designers to make great portable application UIs for iOS and Android. The animation framework in Flutter depends on composed Animation objects. Widgets can either fuse these animations in their build functions straight by perusing their present value and listening to their state changes or they can utilize the animations as the premise of more intricate animations that they give to different widgets.

In this blog, we will Explore AnimatedSize In Flutter. We will see how to implement a demo program of the animated size widget and how to use it in your flutter applications.

AnimatedSize class – widgets library – Dart API
Animated widget that automatically transitions its size over a given duration whenever the given child’s size changes…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

AnimatedSize widget is a widget that consequently advances its anything but a given duration at whatever point the given child’s size changes. It is a widget that animates its size to coordinate with the size of its child.

Demo Module :

This demo video shows how to create an animated size widget in a flutter. It shows how the animated size widget will work in your flutter applications. It shows when the code successfully runs, then the user press the button the size of the child changed according to the given duration. It will be shown on your devices.

Constructor:

There are constructor of AnimatedSize are:

const AnimatedSize({
Key? key,
Widget? child,
this.alignment = Alignment.center,
this.curve = Curves.linear,
required this.duration,
this.reverseDuration,
required this.vsync,
this.clipBehavior = Clip.hardEdge,
})

In the above constructor, all fields set apart with @required should not be vacant argument is really needed since you will get an affirmation error on the off chance that you don’t pass it. There are two required arguments: vsync and duration. Below I am going to explain how to provide the values for the required and non-required arguments.

Properties:

There are some properties of AnimatedSize are:

  • > alignment: This property is utilized to the alignment of the child inside the parent when the parent isn’t yet a similar size as the child. The x and y upsides of the alignment control the horizontal and vertical arrangement, separately.
  • > reverseDuration: This property is utilized to the duration while changing this current widget’s size to coordinate with the child’s size while going reverse.
  • > curve: This property is utilized in the animation curve while progressing this current widget’s size to coordinate with the child’s size.
  • duration: This property is utilized to the duration while changing this current widget’s size to coordinate with the child’s size.
  • vsync: This Property is utilized to will indicate the TickerProvider for this widget.
  • > child: This Property is utilized to the widget underneath this widget in the tree.

Implementation:

Step 1: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

Step 2: 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 animated_size_demo.dart inside the lib folder.

We will create a Stateful widget and the respective State class has to use TickerProviderStateMixin.

class _AnimatedSizeDemoState extends State<AnimatedSizeDemo>
with TickerProviderStateMixin {
}

First, we will create a double variable _size.

double _size = 140;

In the body, we will add the center widget. In this widget, add the column widget. Inside, add the text , _buildAnimatedSize()_buildAnimationWithAnimatedContainer() widgets. We will describe both below.

Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Animated Size",style: TextStyle(fontSize: 18),),
SizedBox(height: 10,),
_buildAnimatedSize(),
SizedBox(height: 50,),
Text("Size Animation With AnimatedContainer",style: TextStyle(fontSize: 18),),
SizedBox(height: 10,),
_buildAnimationWithAnimatedContainer(),
SizedBox(height: 50,),
ElevatedButton(
child: Text('Change Size'),
onPressed: () {
setState(() {
_size = _size == 140 ? 180 : 140;
});
},
)
],
),
),

We will also add an ElevatedButton(). Inside, add text and onPressed function. In function, we will be switching the value of the _size between small value and big value.

We will describe the _buildAnimatedSize() widget:

In this widget, we will return a container with decoration. It’s child property, we will add AnimatedSize() widget. In this widget, we will add vsync, duration with 3 seconds, alignment was center, the curve was easeInCirc and _buildChild() widget.

Widget _buildAnimatedSize() {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
),
child: AnimatedSize(
vsync: this,
duration: const Duration(seconds: 3),
alignment: Alignment.center,
curve: Curves.easeInCirc,
child: _buildChild(),
),
);
}

We will describe the _buildChild() widget:

In this widget, we will return a container. Inside add width, height with double variable _size. We will add DecorationImage with fit: BoxFit.contain.

Widget _buildChild() {
return Container(
width: _size,
height: _size,
decoration: BoxDecoration(
color: Colors.teal[50],
image: DecorationImage(
image: AssetImage(
'assets/logo.png'
),fit: BoxFit.contain
),
),
);
}

We will describe the _buildAnimationWithAnimatedContainer() widget:

The AnimatedSize is utilized to animate a parent widget to coordinate with the size of its child. It doesn’t animate the child widget. On the off chance that what you need is animating the size change of a widget, one of the options is utilizing the AnimatedContainer widget. The AnimatedContainer is a Container that can animate its child when any property changes.

Widget _buildAnimationWithAnimatedContainer() {
return AnimatedContainer(
width: _size,
height: _size,
color: Colors.teal[50],
duration: const Duration(seconds: 3),
child: _buildChild(),
);
}

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

Final Output

Code File:

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


class AnimatedSizeDemo extends StatefulWidget {
@override
_AnimatedSizeDemoState createState() =>
new _AnimatedSizeDemoState();
}

class _AnimatedSizeDemoState extends State<AnimatedSizeDemo>
with TickerProviderStateMixin {

double _size = 140;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Flutter Animated Size Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Animated Size",style: TextStyle(fontSize: 18),),
SizedBox(height: 10,),
_buildAnimatedSize(),
SizedBox(height: 50,),
Text("Size Animation With AnimatedContainer",style: TextStyle(fontSize: 18),),
SizedBox(height: 10,),
_buildAnimationWithAnimatedContainer(),
SizedBox(height: 50,),
ElevatedButton(
child: Text('Change Size'),
onPressed: () {
setState(() {
_size = _size == 140 ? 180 : 140;
});
},
)
],
),
),
);
}

Widget _buildChild() {
return Container(
width: _size,
height: _size,
decoration: BoxDecoration(
color: Colors.teal[50],
image: DecorationImage(
image: AssetImage(
'assets/logo.png'
),fit: BoxFit.contain
),
),
);
}

Widget _buildAnimatedSize() {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
),
child: AnimatedSize(
vsync: this,
duration: const Duration(seconds: 3),
alignment: Alignment.center,
curve: Curves.easeInCirc,
child: _buildChild(),
),
);
}

Widget _buildAnimationWithAnimatedContainer() {
return AnimatedContainer(
width: _size,
height: _size,
color: Colors.teal[50],
duration: const Duration(seconds: 3),
child: _buildChild(),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the AnimatedSize in your flutter projectsWe will show you what the Introduction is?. AnimatedSize can be utilized if you need to animate the size of a parent widget when the size of the child widget changes. The utilization is very basic, you are needed to pass the TickerProvider and Duration arguments. Remember that it doesn’t animate the child widget. 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 a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Explore AnimatedOpacity In Flutter

Related: Explore Hinge Animation In Flutter

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


Explore TypeDef In Dart & Fluter

0

In this blog, we will Explore TypeDef In Dart &Fluter. It tells you the best way to make and utilize typedef in Dart. It likewise works in Flutter and there’s a utilization example in your flutter applications.

In Dart, you can make a type alias to allude to a kind by utilizing typedef keywords. This article discloses how to make typedefs for function and non-function and how to utilize the made typedefs.

Table Of Contents::

How to Using typedef for Functions

Using typedef for Non-Functions

Usage in Flutter

Conclusion



How to Using typedef for Functions:

The typedef keyword was at first made in Dart 1 to allude to functions. In Dart 1, if you need to utilize a function as a variable, field, or boundary, you need to make a typedef first.

To utilize a type alias, you just need to relegate the function mark to a typedef. From that point onward, you can utilize the typedef as a variable, field, or boundary, as displayed in the model beneath.

typedef IntOperation<int> = int Function(int a, int b);

int processTwoInts (IntOperation<int> intOperation, int a, int b) {
return intOperation(a, b);
}

class MyClass {

IntOperation<int> intOperation;

MyClass(this.intOperation);

int doIntOperation(int a, int b) {
return this.intOperation(a, b);
}
}

void main() {
IntOperation<int> sumTwoNumbers = (int a, int b) => a + b;
print(sumTwoNumbers(2, 2));

print(processTwoInts(sumTwoNumbers, 2, 1));

MyClass myClass = MyClass(sumTwoNumbers);
print(myClass.doIntOperation(4, 4));
}

When we run the application, we ought to get the screen’s output like the underneath screen final output:

4
3
8

The following is another model where the function has a generic parameter type.

typedef Compare<T> = bool Function(T a, T b);
bool compareAsc(int a, int b) => a < b;
int compareAsc2(int a, int b) => a - b;

bool doComparison<T>(Compare<T> compare, T a, T b) {
assert(compare is Compare<T>);
return compare(a, b);
}

void main() {
print(compareAsc is Compare<int>);
print(compareAsc2 is Compare<int>);

doComparison(compareAsc, 1, 2);
doComparison(compareAsc2, 1, 2);
}

When we run the application, we ought to get the screen’s output like the underneath screen final output:

true
false
true

Since Dart 2, you can utilize function-type punctuation anyplace. Subsequently, it’s not important to make a typedef any longer. Flutter additionally expresses that the inline function type is liked. That is because individuals who read the code can see the function type straightforwardly. The following is what might be compared to the principal model without typedef.

int processTwoInts (int Function(int a, int b) intOperation, int a, int b) {
return intOperation(a, b);
}

class MyClass {

int Function(int a, int b) intOperation;

MyClass(this.intOperation);

int doIntOperation(int a, int b) {
return this.intOperation(a, b);
}
}

void main() {
int Function(int a, int b) sumTwoNumbers = (int a, int b) => a + b;
print(sumTwoNumbers(2, 2));

print(processTwoInts(sumTwoNumbers, 2, 1));

MyClass myClass = MyClass(sumTwoNumbers);
print(myClass.doIntOperation(4, 4));
}

Nonetheless, it very well may be valuable to make a typedef if the function is long and much of the time utilized.

Using typedef for Non-Functions:

Before Dart 2.13, you can just utilize typedefs for function types. Since Dart 2.13, you can likewise utilize typedefs for making type aliases that allude to non-functions. The use is basically the same, you just need to allow the type to have alluded as a typedef.

In the first place, your Dart form should be version 2.13 or above. For Flutter, you need to utilize version 2.2 or above. You additionally need to refresh the base SDK form in pubspec. yaml to 2.13.0 and run bar get (for Dart) or flutter pub get(for Flutter).

environment:
sdk: '>=2.13.0 <3.0.0'

For instance, you need to characterize a type that stores a list of integer data. For that reason, you can make a typedef whose type is List<int>. Afterward, if you need to characterize a variable for putting away an information show, you can utilize the typedef as the type. In the model underneath, we characterize a typedef considered DataList whose type is List<int>. As you can find in the code beneath, utilizing the typedef gives you similar conduct as utilizing the real type. You can straightforwardly relegate a list value and access the techniques and properties of List. If you check the runtimeType, you’ll get List<int> as the outcome.

typedef DataList = List<int>;

void main() {
DataList data = [50, 60];
data.add(100);
print('length: ${data.length}');
print('values: $data');
print('type: ${data.runtimeType}');
}

When we run the application, we ought to get the screen’s output like the underneath screen final output:

length: 3
values: [50,60,100]
type: List<int>

Not just like a variable, type aliases can likewise be utilized as a field, parameter, and return value of a technique.

typedef DataList = List<int>;

class MyClass {

DataList currentData;

MyClass({required this.currentData});

set data(DataList currentData) {
this.currentData = currentData;
}

ScoreList getMultipliedData(int multiplyFactor) {
DataList result = [];

currentData.forEach((element) {
result.add(element * multiplyFactor);
});

return result;
}
}

void main() {
MyClass myClass = MyClass(currentData: [50, 60, 70]);

myClass.data = [60, 70];
print(myClass.currentData);

print(myClass.getMultipliedData(3));
}

When we run the application, we ought to get the screen’s output like the underneath screen final output:

[70, 90]
[180, 210]

The following is another model. For instance, you need a type for storing request body whose keys and worth types can differ for each type. The Map<String, dynamic> data type is reasonable for that case. Be that as it may, rather than utilizing Map<String, dynamic> each time you need to proclaim a request body variable, you can make a typedef for the type.

typedef RequestBody = Map<String, dynamic>;

void main() {
final RequestBody requestBody1 = {
'type': 'BUY',
'itemId': 2,
'amount': 200,
};
final RequestBody requestBody2 = {
'type': 'CANCEL_BUY',
'orderId': '04567835',
};

print(requestBody1);
print(requestBody2);
}

When we run the application, we ought to get the screen’s output like the underneath screen final output:

{type: BUY, itemId: 2, amount: 200}
{type:
CANCEL_BUY, orderId: 04567835}

You can also define a type alias that has a generic type parameter. The ValueList type alias below has a generic type parameter T. When you define a variable using the type alias, you can pass the generic type to use.

You can likewise characterize a type alias that has a generic type parameter. The NumberList type alias underneath has a nonexclusive type parameter T. At the point when you characterize a variable utilizing the type alias, you can pass the conventional type to utilize.

typedef NumberList<T> = List<T>;

void main() {
NumberList<String> numbers = ['1', '2', '3'];
numbers.add('4');
print('length: ${numbers.length}');
print('numbers: $numbers');
print('type: ${numbers.runtimeType}');
}

When we run the application, we ought to get the screen’s output like the underneath screen final output:

length: 4
numbers: [1, 2, 3, 4]
type: List<String>

Usage in Flutter:

The code beneath is a model for Flutter which makes a typedef for List<Widget> type.

import 'package:flutter/material.dart';

typedef WidgetList = List<Widget>;

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

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: TypedefExample(),
debugShowCheckedModeBanner: false,
);
}
}

class TypedefExample extends StatelessWidget {

WidgetList buildMethod() {
return <Widget>[
const FlutterLogo(size: 60),
const Text('FlutterDevs.com', style: const TextStyle(color: Colors.blue, fontSize: 24)),
];
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo'),
),
body: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: buildMethod(),
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the TypeDef In Dart & Fluter in your projectsThat is how to make and utilize typedefs in Dart/Flutter. You need to allow a type or a function signature to a typedef. Then, at that point, the made typedef can be utilized as a variable, field, parameter, or return value of a strategy. 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 a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Explore Advanced Dart Enum

Related: Explore Sealed Classes In Dart

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


Exploring Text Animations In Flutter

Animations expect a huge part in updating your application’s overall client experience from the visual analysis, motion, and up to the custom animations, you can really imagine!. Like some different things coordinated into an application, animations ought to be helpful rather than basically a normal elaborate format.

Animations are direct to do in Flutter, and a lot of eccentrics can be refined with essentially less effort than native Android.

In this post, we will be Exploring Text Animations In Flutter. We will also implement a demo program of text animations, and show a collection of cool and beautiful text animations using the animated_text_kit package in your flutter applications.

animated_text_kit | Flutter Package
A flutter package that contains a collection of some cool and awesome text animations. Recommended package for text…pub.dev

Table Of Contents ::

Introduction

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

A flutter widget package that contains an assortment of some cool and great content animations. We will make extraordinary and excellent content animations utilizing the animated_text_kit package.

To get a more understanding through the help of video , Please watch:


Properties:

There are some of the properties of AnimatedTextKit are:

  • > animatedTexts: This property is used to list [AnimatedText] to display subsequently in the animation.
  • > isRepeatingAnimation: This property is used to set if the animation should not repeat by changing its value to false. By default, it is set to true.
  • > totalRepeatCount: This property is used to sets the number of times animation should repeat. By default, it is set to 3.
  • > repeatForever: This property is used to sets if the animation should repeat forever. [isRepeatingAnimation] also needs to be set to true if you want to repeat forever.
  • > onFinished: This property is used to adds the onFinished [VoidCallback] to the animated widget. This method will run only if [isRepeatingAnimation] is set to false.
  • > onTap: This property is used to adds the onTap [VoidCallback] to the animated widget.
  • > stopPauseOnTap: This property is used to on pause, should a tap remove the remaining pause time?. By default, it is set to false.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

animated_text_kit: 

Step 2: Import

import 'package:animated_text_kit/animated_text_kit.dart';

Step 3: 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 home_page_screen.dart inside the lib folder.

We will create nine different buttons on the home page screen, and when the user taps on the button, the animation will work. There are different animations on all buttons. We will deeply discuss this below. When we run the application, we ought to get the screen’s output like the underneath screen capture.

Home Screen

> Rotate Animation Text:

In the body, we will add a column widget. In this widget, add a Container with height and width. Its child property, add a _rotate() widget.

Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
decoration: BoxDecoration(color: Colors.red),
height: 300.0,
width: 350.0,
child: Center(
child: _rotate(),
),
),
],
),
)

In the _rotate() widget. We will return the Row widget. Inside, add text and DefaultTextStyle(). It’s child property, we will add AnimatedTextKit() widget. Inside, we will add repeatForever is true, isRepeatingAnimation was also true, and add animatedTexts. In animatedTexts, we will add three RotateAnimatedText(). Users can also add the duration, rotation.

Widget _rotate(){
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(width: 10.0, height: 100.0),
const Text(
'Flutter',
style: TextStyle(fontSize: 40.0),
),
const SizedBox(width: 15.0, height: 100.0),
DefaultTextStyle(
style: const TextStyle(
fontSize: 35.0,
),
child: AnimatedTextKit(
repeatForever: true,
isRepeatingAnimation: true,
animatedTexts: [
RotateAnimatedText('AWESOME'),
RotateAnimatedText('Text'),
RotateAnimatedText('Animation'),
]),
),
],
);
}

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

Rotate Animation Text

> Typer Animation Text:

In the body, we will add the same method as the above. But changes in child property, add a _typer widget.

Widget _typer(){
return SizedBox(
width: 250.0,
child: DefaultTextStyle(
style: const TextStyle(
fontSize: 30.0,
fontFamily: 'popin',
),
child: AnimatedTextKit(
isRepeatingAnimation: true,
animatedTexts: [
TyperAnimatedText('When you talk, you are only repeating'
,speed: Duration(milliseconds: 100)),
TyperAnimatedText('something you know.But if you listen,'
,speed: Duration(milliseconds: 100)),
TyperAnimatedText(' you may learn something new.'
,speed: Duration(milliseconds: 100)),
TyperAnimatedText('– Dalai Lama'
,speed: Duration(milliseconds: 100)),
]
),
),
);
}

In this widget, we will return SizedBox(). Inside, we will add DefaultTextStyle() and add AnimatedTextKit() widget. In this widget, we will add animatedTexts. Inside, we will add four TyperAnimatedText() with speed duration. When we run the application, we ought to get the screen’s output like the underneath screen video.

Typer Animation Text

> Fade Animation Text:

In the body, we will add the same method as the above. But changes in child property, add a _fade widget.

Widget _fade(){
return SizedBox(
child: DefaultTextStyle(
style: const TextStyle(
fontSize: 32.0,
fontWeight: FontWeight.bold,
),
child: Center(
child: AnimatedTextKit(
repeatForever: true,
animatedTexts: [
FadeAnimatedText('THE HARDER!!',
duration: Duration(seconds: 3),fadeOutBegin: 0.9,fadeInEnd: 0.7),
FadeAnimatedText('YOU WORK!!',
duration: Duration(seconds: 3),fadeOutBegin: 0.9,fadeInEnd: 0.7),
FadeAnimatedText('THE LUCKIER!!!',
duration: Duration(seconds: 3),fadeOutBegin: 0.9,fadeInEnd: 0.7),
FadeAnimatedText('YOU GET!!!!',
duration: Duration(seconds: 3),fadeOutBegin: 0.9,fadeInEnd: 0.7),


],
),
),
),
);

}

In this widget, we will return SizedBox(). Inside, we will add DefaultTextStyle() and add AnimatedTextKit() widget. In this widget, we will add animatedTexts. Inside, we will add four FadeAnimatedText() with speed duration, fadeOutBegin, and fadeInEnd. fadeOutBegin was greater than fadeInEnd. When we run the application, we ought to get the screen’s output like the underneath screen video.

Fade Animation Text

> Scale Animation Text:

In the body, we will add the same method as the above. But changes in child property, add a _scale widget.

Widget _scale(){
return SizedBox(
child: DefaultTextStyle(
style: const TextStyle(
fontSize: 50.0,
fontFamily: 'SF',
),
child: Center(
child: AnimatedTextKit(
repeatForever: true,
animatedTexts: [
ScaleAnimatedText('Eat',scalingFactor: 0.2),
ScaleAnimatedText('Code',scalingFactor: 0.2),
ScaleAnimatedText('Sleep',scalingFactor: 0.2),
ScaleAnimatedText('Repeat',scalingFactor: 0.2),

],
),
),
),
);
}

In this widget, we will return SizedBox(). Inside, we will add DefaultTextStyle() and add AnimatedTextKit() widget. In this widget, we will add animatedTexts. Inside, we will add four ScaleAnimatedText() with scalingFactor. scalingFactor was set the scaling factor of the text for the animation. When we run the application, we ought to get the screen’s output like the underneath screen video.

Scale Animation Text

> TextLiquidFill Animation:

In the body, we will add the same method as the above. But changes in child property, add a _textLiquidFillAnimation widget.

Widget _textLiquidFillAnimation(){
return SizedBox(
child: Center(
child: TextLiquidFill(
text: 'Flutter Devs',
waveDuration: Duration(seconds: 5),
waveColor: Colors.blue,
boxBackgroundColor: Colors.green,
textStyle: TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.bold,
),
),
),
);
}

In this widget, we will return SizedBox(). Inside, we will add TextLiquidFill() widget. In this widget, we will add text, waveDuration, waveColor, and boxBackgroundColor. When we run the application, we ought to get the screen’s output like the underneath screen video.

TextLiquidFill Animation

> Wavy Animation Text:

In the body, we will add the same method as the above. But changes in child property, add a _wave widget.

Widget _wavy(){
return DefaultTextStyle(
style: const TextStyle(
fontSize: 25.0,
),
child: AnimatedTextKit(
animatedTexts: [
WavyAnimatedText("Flutter is Google's UI toolkit,",
speed: Duration(milliseconds: 200)),
WavyAnimatedText('for building beautiful Apps',
speed: Duration(milliseconds: 200)),
],
isRepeatingAnimation: true,
repeatForever: true,
),
);
}

In this widget, we will return DefaultTextStyle(). Inside, we will add AnimatedTextKit() widget. In this widget, we will add animatedTexts. Inside, we will add two WavyAnimatedText() with the speed duration of the text. When we run the application, we ought to get the screen’s output like the underneath screen video.

Wavy Animation Text

> Flicker Animation Text:

In the body, we will add the same method as the above. But changes in child property, add a _flicker widget.

Widget _flicker(){
return SizedBox(
width: 250.0,
child: DefaultTextStyle(
style: const TextStyle(
fontSize: 30,
),
child: AnimatedTextKit(
repeatForever: true,
animatedTexts: [
FlickerAnimatedText('FlutterDevs specializes in creating,',
speed: Duration(milliseconds: 1000),entryEnd: 0.7),
FlickerAnimatedText('cost-effective and',
speed: Duration(milliseconds: 1000),entryEnd: 0.7),
FlickerAnimatedText("efficient applications!",
speed: Duration(milliseconds: 1000),entryEnd: 0.7),
],
),
),
);

}

In this widget, we will return SizedBox(). Inside, we will add DefaultTextStyle() and add AnimatedTextKit() widget. In this widget, we will add animatedTexts. Inside, we will add four FlickerAnimatedText() with entryEnd and speed. entryEnd was marked ending of flickering entry interval of text. When we run the application, we ought to get the screen’s output like the underneath screen video.

Flicker Animation Text

> Colorize Animation Text:

In the body, we will add the same method as the above. But changes in child property, add a _colorize widget.

Widget _colorize(){
return SizedBox(
child: Center(
child: AnimatedTextKit(
animatedTexts: [
ColorizeAnimatedText(
'Mobile Developer',
textStyle: colorizeTextStyle,
colors: colorizeColors,
),
ColorizeAnimatedText(
'Software Testing',
textStyle: colorizeTextStyle,
colors: colorizeColors,
),
ColorizeAnimatedText(
'Software Engineer',
textStyle: colorizeTextStyle,
colors: colorizeColors,
),
],
isRepeatingAnimation: true,
repeatForever: true,
),
),
);


}

In this widget, we will return SizedBox(). Inside, we will add add AnimatedTextKit() widget. In this widget, we will add animatedTexts. Inside, we will add three ColorizeAnimatedText() with textStyle and colors.

List<MaterialColor> colorizeColors = [
Colors.red,
Colors.yellow,
Colors.purple,
Colors.blue,
];

static const colorizeTextStyle = TextStyle(
fontSize: 40.0,
fontFamily: 'SF',
);

Users can change color according to text. When we run the application, we ought to get the screen’s output like the underneath screen video

Colorize Animation Text

> Typewriter Animation Text:

In the body, we will add the same method as the above. But changes in child property, add a _typeWriter widget.

Widget _typeWriter(){
return SizedBox(
child: DefaultTextStyle(
style: const TextStyle(
fontSize: 30.0,
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: AnimatedTextKit(
repeatForever: true,
animatedTexts: [
TypewriterAnimatedText('FlutterDevs specializes in creating cost-effective',
curve: Curves.easeIn,speed: Duration(milliseconds: 80)),
TypewriterAnimatedText('and efficient applications with our perfectly crafted,',
curve: Curves.easeIn,speed: Duration(milliseconds: 80)),
TypewriterAnimatedText('creative and leading-edge flutter app development solutions',
curve: Curves.easeIn,speed: Duration(milliseconds: 80)),
TypewriterAnimatedText('for customers all around the globe.',
curve: Curves.easeIn,speed: Duration(milliseconds: 80)),
],
),
),
),
),
);

}

In this widget, we will return SizedBox(). Inside, we will add DefaultTextStyle() and add AnimatedTextKit() widget. In this widget, we will add animatedTexts. Inside, we will add four TypewriterAnimatedText() with curve and speed. When we run the application, we ought to get the screen’s output like the underneath screen video.

Typewriter Animation Text

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_animation_text/colorize_animation_text.dart';
import 'package:flutter_animation_text/fade_animation_text.dart';
import 'package:flutter_animation_text/flicker_animation_text.dart';
import 'package:flutter_animation_text/rotate_animation_text.dart';
import 'package:flutter_animation_text/scale_animation_text.dart';
import 'package:flutter_animation_text/text_liquid_fill_animation.dart';
import 'package:flutter_animation_text/typer_animation_text.dart';
import 'package:flutter_animation_text/typewriter_animated_text.dart';
import 'package:flutter_animation_text/wavy_animation_text.dart';


class HomePageScreen extends StatefulWidget {
@override
_HomePageScreenState createState() => _HomePageScreenState();
}

class _HomePageScreenState extends State<HomePageScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xffFFFFFF),
appBar: AppBar(
backgroundColor: Colors.black,
title: Text('Flutter Animations Text Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[

// ignore: deprecated_member_use
RaisedButton(
child: Text('Rotate Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => RotateAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),
),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
child: Text('Typer Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => TyperAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
child: Text('Fade Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => FadeAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
child: Text('Scale Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => ScaleAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
child: Text('TextLiquidFill Animation',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => TextLiquidFillAnimation()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
child: Text('Wavy Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => WavyAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
child: Text('Flicker Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => FlickerAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),
// ignore: deprecated_member_use
RaisedButton(
child: Text('Colorize Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => ColorizeAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),

// ignore: deprecated_member_use
RaisedButton(
child: Text('Typewriter Animation Text',style: TextStyle(color: Colors.black),),
color: Colors.tealAccent,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => TypewriterAnimationText()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),

],
),
)
), //center
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Text Animations in your flutter projects. We will show you what the Introduction is?, some properties using in AnimatedTextKit, and make a demo program for working Text Animations 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.

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

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

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Exploring AnimatedModalBarrier In Flutter

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


Custom Chat Bubble In Flutter

0

Conversation chat applications show messages in chat rises with strong shading backgrounds. Modern chat applications show chat bubbles with slopes that depend on the bubbles’ situation on the screen. There are times when we need to utilize a chat bubble in our flutter application. Yet, utilizing a library for a particularly inconsequential errand isn’t great.

In this blog, we will explore the Custom Chat Bubble In Flutter. We will see how to implement a demo program of the custom chat bubble and how to make a custom chat bubble most simply without using any third-party libraries in your flutter applications.

Table Of Contents::

Flutter

Implementation

Code Implement

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 ”

It is free and open-source. It was at first evolved from Google and presently overseen by an ECMA standard. Flutter applications utilize the Dart programming language for making an application. The dart programming shares a few same highlights as other programming dialects, like Kotlin and Swift, and can be trans-arranged into JavaScript code.

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

Implementation:

Step 1: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/images/

Step 2: 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 custom_shape.dart inside the lib folder.

First, create the custom shape Custom Painter class. This will be used to draw the custom shape at the end of the chat bubble. Users can add any color in custom shape.

import 'package:flutter/material.dart';

class CustomShape extends CustomPainter {
final Color bgColor;

CustomShape(this.bgColor);

@override
void paint(Canvas canvas, Size size) {
var paint = Paint()..color = bgColor;

var path = Path();
path.lineTo(-5, 0);
path.lineTo(0, 10);
path.lineTo(5, 0);
canvas.drawPath(path, paint);
}

@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}

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

First, we will create a constructer final string message.

final String message;
const SentMessageScreen({
Key key,
@required this.message,
}) : super(key: key);

In the build method, we will return Padding(). Inside, we will add the Row() widget. In this widget, we will add the mainAxisAlignment was the end and add the messageTextGroup. We will define the below code.

return Padding(
padding: EdgeInsets.only(right: 18.0, left: 50, top: 15, bottom: 5),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
SizedBox(height: 30),
messageTextGroup,
],
),
);

We will deeply define messageTextGroup:

We will create a final messageTextGroup is equal to the Flexible() widget. In this widget, we will add the Row() widget. Inside, add mainAxisAlignment was the end and crossAxisAlignment was started. Inside children, we will add Conatiner with decoration box and add color, borderRadius. It’s child property, we will add a variable message text. We will add CustomPaint(), we will use the above painter class was CustomShape with color.

final messageTextGroup = Flexible(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: Container(
padding: EdgeInsets.all(14),
decoration: BoxDecoration(
color: Colors.cyan[900],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(18),
bottomLeft: Radius.circular(18),
bottomRight: Radius.circular(18),
),
),
child: Text(
message,
style: TextStyle(color: Colors.white, fontSize: 14),
),
),
),
CustomPaint(painter: CustomShape(Colors.cyan[900])),
],
));

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

Similarly, We can now create a received message screen. We just need to flip the custom shape and put it in the start instead of the end. We will use the transform widget to flip the custom shape widget. In the transform widget, we will add alignment was center and transform was Matrix4.rotationY(math. pi).

final messageTextGroup = Flexible(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Transform(
alignment: Alignment.center,
transform: Matrix4.rotationY(math.pi),
child: CustomPaint(
painter: CustomShape(Colors.grey[300]),
),
),
Flexible(
child: Container(
padding: EdgeInsets.all(14),
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.only(
topRight: Radius.circular(18),
bottomLeft: Radius.circular(18),
bottomRight: Radius.circular(18),
),
),
child: Text(
message,
style: TextStyle(color: Colors.black, fontSize: 14),
),
),
),
],
));

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

In the body, we will add a Container() widget. Inside, add decoration box and add image. It’s child property, we can add both send and received message screens in our ListView().

Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/bg_chat.jpg"),
fit: BoxFit.cover)),
child: ListView(
children: [
SentMessageScreen(message: "Hello"),
ReceivedMessageScreen(message: "Hi, how are you"),
SentMessageScreen(message: "I am great how are you doing"),
ReceivedMessageScreen(message: "I am also fine"),
SentMessageScreen(message: "Can we meet tomorrow?"),
ReceivedMessageScreen(message: "Yes, of course we will meet tomorrow"),
],
),
),

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

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_custom_chat_bubble/received_message_screen.dart';
import 'package:flutter_custom_chat_bubble/send_messsage_screen.dart';

class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;

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

class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.cyan[900],
automaticallyImplyLeading: false,
title: Text(widget.title),
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/bg_chat.jpg"),
fit: BoxFit.cover)),
child: ListView(
children: [
SentMessageScreen(message: "Hello"),
ReceivedMessageScreen(message: "Hi, how are you"),
SentMessageScreen(message: "I am great how are you doing"),
ReceivedMessageScreen(message: "I am also fine"),
SentMessageScreen(message: "Can we meet tomorrow?"),
ReceivedMessageScreen(message: "Yes, of course we will meet tomorrow"),
],
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Custom Chat Bubble in your flutter projectsWe will make a demo program for working Custom Chat Bubble using any third-party libraries 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.

find the source code of the Flutter Custom Chat Bubble:

flutter-devs/flutter_custom_chat_bubble
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


From Our Parent Company Aeologic

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

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

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

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

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

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