Google search engine
Home Blog Page 20

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.


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.


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.


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.


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.


Custom Animated BottomNavigation Bar In Flutter

0

The bottom navigation bar is a cool widget that has been given by the flutter system. We can undoubtedly add the bottom navigation bar to the platform. In the framework, there is a characteristic called bottomNavigationBar and we can dole out BottomNavigationBar for that. Inside the BottomNavigationBar class we can characterize the navigation catch’s conduct and what are the catches need to show inside the bar.

In this blog, we will explore the Custom Animated BottomNavigation Bar In Flutter. We will see how to implement a demo program of the custom animated bottomnavigation bar and how to use it in your flutter applications.

Table Of Contents::

Introduction

Properties

Code Implement

Code File

Conclusion



Introduction:

A material widget that is shown at the bottom of an application for choosing among few perspectives, ordinarily somewhere in the range of three and five. The bottom navigation bar comprises various items as text labels, icons, or both, spread out on top of a piece of material. It gives fast navigation between the high-level perspectives on an application. For bigger screens, side navigation might be a superior fit.

A bottom navigation bar is normally utilized related to a Scaffold, where it is given as the Scaffold.bottomNavigationBar contention.

Demo Module :

This demo video shows how to use a custom bottomNavigation bar in a flutter. It shows how the custom bottomnavigation bar will work in your flutter applications. It shows when the user taps on the bottom navigation bar icon, then they will be animated and show with label text also. When the user taps any icon the color was also changes and animated. It will be shown on your device.

Properties:

There are some properties of custom animated bottom navigation bar are:

  • > selectedIndex: This property is used to the selected item is an index. Changing this property will change and animate the item being selected. Defaults to zero.
  • > backgroundColor: This property is used to the background color of the navigation bar. It defaults to Theme.bottomAppBarColor if not provided.
  • > showElevation: This property is used to whether this navigation bar should show an elevation. Defaults to true.
  • > List<BottomNavyBarItem> items: This property is used to defines the appearance of the buttons that are displayed in the bottom navigation bar. This should have at least two items and five at most.
  • > onItemSelected: This property is used callback that will be called when an item is pressed.
  • > curve: This property is used to configure the animation curve.
  • > itemCornerRadius: This property is used to the items corner radius, if not set, it defaults to 50.

How to implement code in dart file :

You need to implement it in your code respectively:

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

In a build method, we will return a scaffold(). Inside we will add an appBar. In appBar, we will add title and backgroundColor. We will add body and add inside the getBody() widget. We will deeply define the code below. Now, we will add bottomNavigationBar and add it inside the _buildBottomBar() widget. We will also deeply define the code below.

return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text("Custom Animated Bottom Navigation Bar"),
backgroundColor: Colors.green[200],
),
body: getBody(),
bottomNavigationBar: _buildBottomBar()
);

We will deeply define getBody() widget

First, we will create an integer variable _currentIndex is equal to zero.

int _currentIndex = 0;

We will create getBody() widget. In this widget, we will add List<Widget> pages. We will add four containers with different texts and return IndexedStack() widget. Inside the widget, we will add the index was my variable _currentIndex and children was list widget pages.

Widget getBody() {
List<Widget> pages = [
Container(
alignment: Alignment.center,
child: Text("Home",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold),),
),
Container(
alignment: Alignment.center,
child: Text("Users",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold),),
),
Container(
alignment: Alignment.center,
child: Text("Messages",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold),),
),
Container(
alignment: Alignment.center,
child: Text("Settings",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold),),
),
];
return IndexedStack(
index: _currentIndex,
children: pages,
);
}

We will deeply define _buildBottomBar() widget

First, we will create a final variable that was _inactiveColor is equal to the grey color.

final _inactiveColor = Colors.grey;

We will create a _buildBottomBar() widget. In this widget, we will return a CustomAnimatedBottomBar(). Inside, we will add a container height, backgroundColor, selectedIndex was added variable _currentIndex, showElevation, the curve of animation, onItemSelected and items. In items, e will add four BottomNavyBarItem(). Inside, we will add four different icons, titles, activeColors, and all text-align should be center.

Widget _buildBottomBar(){
return CustomAnimatedBottomBar(
containerHeight: 70,
backgroundColor: Colors.black,
selectedIndex: _currentIndex,
showElevation: true,
itemCornerRadius: 24,
curve: Curves.easeIn,
onItemSelected: (index) => setState(() => _currentIndex = index),
items: <BottomNavyBarItem>[
BottomNavyBarItem(
icon: Icon(Icons.apps),
title: Text('Home'),
activeColor: Colors.green,
inactiveColor: _inactiveColor,
textAlign: TextAlign.center,
),
BottomNavyBarItem(
icon: Icon(Icons.people),
title: Text('Users'),
activeColor: Colors.purpleAccent,
inactiveColor: _inactiveColor,
textAlign: TextAlign.center,
),
BottomNavyBarItem(
icon: Icon(Icons.message),
title: Text(
'Messages ',
),
activeColor: Colors.pink,
inactiveColor: _inactiveColor,
textAlign: TextAlign.center,
),
BottomNavyBarItem(
icon: Icon(Icons.settings),
title: Text('Settings'),
activeColor: Colors.blue,
inactiveColor: _inactiveColor,
textAlign: TextAlign.center,
),
],
);
}

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

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

class CustomAnimatedBottomBar extends StatelessWidget {

CustomAnimatedBottomBar({
Key? key,
this.selectedIndex = 0,
this.showElevation = true,
this.iconSize = 24,
this.backgroundColor,
this.itemCornerRadius = 50,
this.containerHeight = 56,
this.animationDuration = const Duration(milliseconds: 270),
this.mainAxisAlignment = MainAxisAlignment.spaceBetween,
required this.items,
required this.onItemSelected,
this.curve = Curves.linear,
}) : assert(items.length >= 2 && items.length <= 5),
super(key: key);

final int selectedIndex;
final double iconSize;
final Color? backgroundColor;
final bool showElevation;
final Duration animationDuration;
final List<BottomNavyBarItem> items;
final ValueChanged<int> onItemSelected;
final MainAxisAlignment mainAxisAlignment;
final double itemCornerRadius;
final double containerHeight;
final Curve curve;

@override
Widget build(BuildContext context) {
final bgColor = backgroundColor ?? Theme.of(context).bottomAppBarColor;

return Container(
decoration: BoxDecoration(
color: bgColor,
boxShadow: [
if (showElevation)
const BoxShadow(
color: Colors.black12,
blurRadius: 2,
),
],
),
child: SafeArea(
child: Container(
width: double.infinity,
height: containerHeight,
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
child: Row(
mainAxisAlignment: mainAxisAlignment,
children: items.map((item) {
var index = items.indexOf(item);
return GestureDetector(
onTap: () => onItemSelected(index),
child: _ItemWidget(
item: item,
iconSize: iconSize,
isSelected: index == selectedIndex,
backgroundColor: bgColor,
itemCornerRadius: itemCornerRadius,
animationDuration: animationDuration,
curve: curve,
),
);
}).toList(),
),
),
),
);
}
}

class _ItemWidget extends StatelessWidget {
final double iconSize;
final bool isSelected;
final BottomNavyBarItem item;
final Color backgroundColor;
final double itemCornerRadius;
final Duration animationDuration;
final Curve curve;

const _ItemWidget({
Key? key,
required this.item,
required this.isSelected,
required this.backgroundColor,
required this.animationDuration,
required this.itemCornerRadius,
required this.iconSize,
this.curve = Curves.linear,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return Semantics(
container: true,
selected: isSelected,
child: AnimatedContainer(
width: isSelected ? 130 : 50,
height: double.maxFinite,
duration: animationDuration,
curve: curve,
decoration: BoxDecoration(
color:
isSelected ? item.activeColor.withOpacity(0.2) : backgroundColor,
borderRadius: BorderRadius.circular(itemCornerRadius),
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: NeverScrollableScrollPhysics(),
child: Container(
width: isSelected ? 130 : 50,
padding: EdgeInsets.symmetric(horizontal: 8),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
IconTheme(
data: IconThemeData(
size: iconSize,
color: isSelected
? item.activeColor.withOpacity(1)
: item.inactiveColor == null
? item.activeColor
: item.inactiveColor,
),
child: item.icon,
),
if (isSelected)
Expanded(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 4),
child: DefaultTextStyle.merge(
style: TextStyle(
color: item.activeColor,
fontWeight: FontWeight.bold,
),
maxLines: 1,
textAlign: item.textAlign,
child: item.title,
),
),
),
],
),
),
),
),
);
}
}
class BottomNavyBarItem {

BottomNavyBarItem({
required this.icon,
required this.title,
this.activeColor = Colors.blue,
this.textAlign,
this.inactiveColor,
});

final Widget icon;
final Widget title;
final Color activeColor;
final Color? inactiveColor;
final TextAlign? textAlign;

}

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

Final Outputs

Code File:

https://gist.github.com/ShaiqAhmedkhan/957f90099841815e016d70785248db3a#file-my_home_page_screen-dart

Conclusion:

In the article, I have explained the basic structure of the Custom Animated BottomNavigation Bar in a flutter; you can modify this code according to your choice. This was a small introduction to Custom Animated BottomNavigation Bar 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 Custom Animated BottomNavigation Bar in your flutter projects. We will show you what the Introduction is?, some properties and make a demo program for working Custom Animated BottomNavigation Bar and show when the user taps on the bottom navigation bar icon, then they will be animated and show with label text also. When the user taps any icon the color was also changed and animated 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.


Explore Asynchrony Primer for Dart & Flutter

0

Dart is a single-threaded language. This characteristic is frequently misconstrued. Numerous software engineers accept this implies Dart can’t run code equally, however that is not the situation. So how does Dart oversee and execute tasks?.

In this article, We are going to learn about Explore Asynchrony Primer for Dart & Flutter. Flutter applications start with a single execution process to manage to execute code. How dart manages execute operations in your applications.

Table Of Contents::

Isolates

Asynchrony and the event loop

What’s in a thread?

Microtasks

Events

Future with Async & Await

Conclusion



Isolates:

At the point when you start a Dart application (with or without Flutter), the Dart runtime dispatches another string cycle for it. Threads are displayed as isolates, supposed because the runtime keeps each disconnects its overseeing totally isolated from the others. Each has its own memory space, which forestalls the requirement for memory locking to keep away from race conditions, and each has its own event queues and activities. For some applications, this fundamental isolate is what each of the coders should be worried about, however, it is feasible to produce new isolates to run long or arduous calculations without obstructing the program’s primary isolate.

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

Isolates can speak with one another just through a basic informing convention. They can’t get to one another’s memory straightforwardly. Code execution inside an individual separate is single-threaded, implying that only each activity executes in turn. This is the place where asynchronous programming designs come in. You go through them to abstain from locking the isolate while trusting that protracted tasks will finish, for example, network access.

Isolates are:

  • Dart’s version of Threads.
  • Isolate memory isn’t shared.
  • Utilizes Ports and Messages to convey between them.
  • May utilize another processor core if accessible.
  • Runs code in parallel.

Asynchrony and the event loop:

A great deal of your Dart code runs inside your application’s isolate synchronously. Since an individual isolate is single-threaded, just a single activity can be executed at a time, so when performing long assignments, it’s feasible to obstruct the thread. At the point when the thread is kept occupied along these lines, there’s no ideal opportunity for reacting to client communication events or refreshing the screen. This can cause your application to feel inert or delayed to your clients, and baffled clients abandon applications rapidly.

Here is an illustration of a synchronous Dart function:

void syncFunction() {
var count = 0;

for (int i = 0; i < 1000; i++) {
count++;
}
}

On current registering devices, even this loop that counts to a thousand will execute decently fast, however, while it’s occurring, no other code inside your Dart isolate can execute. The thread is supposed to be impeded; it’s accomplishing something, yet the attention is altogether on that one thing until it’s finished. If the client taps a button while this function is running, they’ll get no reaction until syncFunction() exits.

What’s in a thread?:

At the point when a Dart (or Flutter) application is executed, the Dart runtime makes an isolated string measure for it. For that thread, two lines are introduced, one for microtasks and one for events, and both are FIFO (first-in, first-out) lines. With those setups, the application’s main() work is executed. When that code wraps up executing, the event loop is dispatched. For the existence of the interaction, microtasks and events will enter their particular lines and are each dealt with in their chance by the event loop. The event loop resembles an infinite loop where Dart over and again checks for microtasks and events to deal with while another code isn’t being run.

The image is represented in the following diagram:

Your application invests the greater part of its time in this event loop, running code for microtasks and events. When nothing dire necessitates consideration, things like the garbage collector for opening up unused memory might be set off.

Microtasks

Microtasks are proposed to be shortcode errands that should be executed asynchronously, yet that ought to be finished before returning control to the event loop. They have a higher need than events, as are constantly taken care of before the event queue is checked. It’s moderately uncommon for a regular Flutter or Dart application to add code to the microtask queue, yet doing so would look something like this:

void updateState() {
myState = "State";

scheduleMicro(() {
rebuild(myState);
});
}

You pass scheduleMicro() a function to be run. In the model, we’ve passed a mysterious function with only one line of code, which calls the anecdotal rebuild() work. The mysterious callback will be executed after some other holding up microtasks have finished, yet additionally after updateState() have returned because the execution is asynchronous.

Keep microtask callbacks short and fast. Since the microtask queue has a higher need than the event queue, long cycles executing as microtasks will hold standard events back from being handled, which may bring about an inert application until preparing finishes.

Events

Once no more microtasks are waiting for consideration, any events sitting in the event queue are taken care of. Between the times your application starts and closures, numerous events will be made and executed.

Some illustration of events are:

  • User input: When users associate with your application, events are put in the event queue, and the application can react properly.
  • I/O with a local storage device or network: Getting or setting information over associations with dormancy are taken care of as asynchronous events.
  • Timers: Through events, code can be executed at a particular point future on or even occasionally.
  • Futures: At the point when a future finishes, an event is embedded into the event queue for later preparation.
  • Streams: As information is added to a stream, listeners are notified utilizing events.

At the point when buttons get tapped by users or organization reactions show up, the code to be executed accordingly is gone into the event queue and run when it arrives at the front of the queue. The equivalent is valid for futures that get finished or streams that obtain new values to disperse. With this asynchronous model, a Dart program can deal with events that happen eccentrically while keeping the UI responsive to input from users.

Future with Async & Await:

An async and await keywords you may use in Dart, towards a Future. When running async code:

  • It runs in the same Isolate(Thread) that started it.
  • Runs all the while (not equal) simultaneously as other code, in the same Isolate(Thread).

It is critical, in that it doesn’t obstruct other code from running in a comparative thread. Especially generous when you are in the principle UI Thread. It will by and large assistance keep your UI smooth while managing numerous events happening in your code.

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Explore Asynchrony Primer for Dart & Flutter in your flutter projectsSince you comprehend the rudiments of Dart’s single-threaded isolates, and how microtasks and events empower asynchronous preparation. So please try it.

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.


Prototype Design Patterns For Dart & Flutter

0

Sometimes you want to make a duplicate, or clone, of a current object. For mutable objects with changing properties, you might require a different copy of an object to try not to ruin the first.

For immutable items, where properties can be instated but never modified, particularly those with extended or expensive introduction schedules (for example network calls, and so on), making a duplicate may be more proficient than making another instance. These can be fundamental abilities while working with Dart or Flutter applications.

This blog will explore Prototype Design Patterns for Dart & Flutter. We will perceive how to execute a demo program. Learn how to implement and use it in your flutter applications.

Table Of Contents::

Introduction

Advantages of Prototype Design Pattern

Cloning Mutable Objects

Cloning Immutable Objects

Conclusion



Introduction:

The prototype design pattern is a creational configuration design in software development. It is utilized when the object is not entirely settled by a prototypical case, which is cloned to create new items.

This pattern is utitlized to:

  • > stay away from the subclasses of an object maker in the client application, as the factory strategy design does.
  • > keep away from the inherent expense of making another object in the standard manner (e.g., utilizing the ‘new’ keyword) when it is restrictively costly for a given application.

To execute the pattern, proclaim a theoretical base class that determines an unadulterated virtual clone() technique. Any sort that needs a “polymorphic constructor” capacity gets itself from the abstract base class and carries out the clone() operation.

The Prototype design is tied in with making an object liable for its cloning. Code outside an item can duplicate by making a void new example and replicating every property throughout each in turn, however, imagine a scenario where the object has private properties.

Assuming that an item incorporates its cloning strategy, private properties will not be missed, and just the actual object should know about its inside structure.

Advantages of Prototype Design Pattern:

  • > Adding and eliminating items at run-time— Models let you integrate another substantial item class into a framework just by enrolling a prototypical case with the client. That is a bit more adaptable than other creational designs because a client can introduce and eliminate prototypes at run-time.
  • > Determining new objects by fluctuating values — Exceptionally powerful frameworks let you characterize recent conduct through object composition by indicating values for an item’s factors and not by characterizing new classes.
  • > Indicating new objects by shifting structure —Numerous applications assemble objects from parts and subparts. For comfort, such applications frequently let you start up complex, client-characterized designs to utilize a particular subcircuit over and over.
  • > Decreased subclassing — The factory Method frequently delivers an order of Creator classes that matches the item class progressive system. The Prototype design allows you to clone a model as opposed to requesting that a factory strategy make another item. Consequently, you needn’t bother with a Creator class order by any stretch of the imagination.

Cloning Mutable Objects:

This is the manner by which you could make a duplicate of a mutable item that can’t clone itself in the Dart language:

class Point {
int y;
int z;

Point([this.y, this.z]);
}

final p1 = Point(4, 9);
final p2 = Point(p1.y, p1.z);
final p3 = Point()
..y = p1.y
..z = p1.z;

The Point class has two public, alterable properties, y, and z. With such a little, straightforward class, it’s insignificant to create duplicates of p1 either with the class’ constructor or by setting the properties on an uninitialized new item with Dart’s cascade operator (..).

The large disadvantage to this approach is that our application code is presently firmly coupled to the Point class, requiring information on its internal operations to create a duplicate. Any progressions to Point imply that application code, conceivably in many spots, will require matching changes, a drawn-out and error-prone situation.

The Prototype design directs that objects ought to be answerable for their own cloning, as so:

class Point {
  int y;
  int z;

 Point([this.y, this.z]);

Point clone() => Point(y, z);
}
final p1 = Point(4, 9);
final p2 = p1.clone();

This is a lot of cleaners, and presently the application code won’t be changed regardless of whether Point gets new or various properties later on, as clone() will continuously return another occurrence of Point with similar values.

Cloning Immutable Objects:

A similar strategy works fine in any event when we make Point immutable:

class Point {
final int y;
final int z;

const Point(this.y, this.z);

Point clone() => Point(y, z);
}

final p1 = Point(4, 9);
final p2 = p1.clone();

In this adaptation, the constructor boundaries are not discretionary, and the class’ member variables can’t be refreshed once introduced. This doesn’t influence our capacity to make clones. Be that as it may, this class doesn’t have an effective method for changing only either of the properties.

In Immutable Data Structures In Dart & Flutter, you can see that adding a copyWith() technique gives us greater adaptability with immutable items:

class Point {
final int y;
final int z;
const Point(this.y, this.z);

Point copyWith({int y, int z}) {
return Point(
y?? this.y,
z?? this.z,
);
}
Point clone() => copyWith(y: y, z: z);
}

final p1 = Point(4, 9);
final p2 = p1.clone();

Here, the copyWith() strategy permits you to make another Point from a current one while changing just individual properties. Likewise, the clone() strategy can utilize to deliver a full object duplicate, keeping us from being required to characterize a different interaction for cloning.

Conclusion:

I hope this blog will provide you with sufficient information on Trying up the Prototype Design Patterns for Dart & Flutter in your projectsThe Prototype design is utilized widely in the Flutter structure, especially while controlling themes, so a working knowledge of it will work well for you.

Its fundamental way of thinking is that an object itself is in the best situation to create its clones, having full admittance to every one of its properties and internal functions. The pattern additionally keeps outer code from requiring detailed information on an object’s execution, continuing to couple free.

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


Generate Strong Random Password In Flutter

0

Flutter just intrigued me with the pleasant UI stuff you could do effectively, and obviously, it permits you to create for both platforms simultaneously. The focal reason for existing is to construct the application out of widgets. It portrays how your application view should look with their present setup and state. When you modified the code, the widget rebuilt its depiction by computing the contrast between the past and current widget to decide the negligible changes for rendering in the UI of the application.

In this blog, we will explore the Generate Strong Random Password In Flutter. We will implement a generated random password demo program and learn how to create a strong random password generate in your flutter applications.

Table Of Contents::

Generate Random Password

Code Implement

Code File

Conclusion



Generate Random Password:

We can undoubtedly create complex passwords and use them for your client accounts. Pick length and chars to be utilized and produce your passwords securely.

Demo Module :

This demo video shows how to create a generate strong random password in a flutter. It shows how the generate strong random password will work in your flutter applications. When the user taps the button then, the password will generate with the combination of length, character, number, special, lower alphabet, and upper alphabet. It will generate on the text form field and the user also copies the generated password. It will be shown on your device.

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the body part, we will add Container. Inside, we will add a Column widget. In this widget, we will add mainAxisAlignmnet and crossAxisAlignmnet was center. We will add text and wrap it to the row.

Container(
padding: EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
children: [
Text("Generate Strong Random Password",style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold
),),
],
SizedBox(height: 15,),
TextFormField(),
SizedBox(height: 15,),
buildButtonWidget()
),
],
),),

Now we will add TextFormFeld, we will make a variable of _contoller is equal to the TextEditingController().

final _controller = TextEditingController();

We will true read-only because the password was generated not editing. We will false the enableInteractiveSelection and add InputDecoration for border.

TextFormField(
controller: _controller,
readOnly: true,
enableInteractiveSelection: false,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.cyan,),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.cyan),
),
),
),

We will also create a dispose() method to dispose the controller

@override
void dispose() {
_controller.dispose();
super.dispose();
}

In TextFormField, we will also create a suffixIcon. Inside, we will add the IconButton(). We will add a copy icon and onPressed method. In the onPressed method, we will add final data is equal to the ClipboardData and in the bracket, we will add _controller. text and set the data on the clipboard. We will show a snackbar when the copy icon is pressed then show a message was “Password Copy”.

suffixIcon: IconButton(
onPressed: (){
final data = ClipboardData(text: _controller.text);
Clipboard.setData(data);

final snackbar = SnackBar(
content: Text("Password Copy"));

ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(snackbar);
},
icon: Icon(Icons.copy))

Now we will create a buildButtonWidget()

We will create buildButtonWidget(), Inside we will return a ElevatedButton(). In this button, we will add the style of ElevatedButton and add the child property. We will add the text “Password Generate” and add the onPressed function in the child property. In this function, we will add a final password is equal to the generatePassword(). We will deeply describe below the generatePassword(). Add the _controller. text is equal to the password.

Widget buildButtonWidget() {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.black
),
onPressed: (){
final password = We will deeply describe;
_controller.text = password;
},
child: Text("Password Generate",style: TextStyle(color: Colors.white),)
);
}

We will deeply describe generatePassword():

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

We will create a String generatePassword()method. Inside, we will add final length is equal to the 20, letterLowerCase, letterUpperCase, number, special character. When we use a strong password then true all bool letters, isNumber, and isSpecial. Add String chars and return List. generate(). Add final indexRandom is equal to the Random.secure().nextInt(chars.length) and return chars [indexRandom].

import 'dart:math';

String generatePassword({
bool letter = true,
bool isNumber = true,
bool isSpecial = true,
}) {
final length = 20;
final letterLowerCase = "abcdefghijklmnopqrstuvwxyz";
final letterUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
final number = '0123456789';
final special = '@#%^*>\$@?/[]=+';

String chars = "";
if (letter) chars += '$letterLowerCase$letterUpperCase';
if (isNumber) chars += '$number';
if (isSpecial) chars += '$special';


return List.generate(length, (index) {
final indexRandom = Random.secure().nextInt(chars.length);
return chars [indexRandom];
}).join('');
}

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/services.dart';
import 'package:flutter_generate_strong_random/custom.dart';

class GeneratePassword extends StatefulWidget {
@override
_GeneratePasswordState createState() => _GeneratePasswordState();
}

class _GeneratePasswordState extends State<GeneratePassword> {

final _controller = TextEditingController();

@override
void dispose() {
_controller.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) =>
Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.cyan,
title: Text('Flutter Generate Random Password'),
),
body: Container(
padding: EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
children: [
Text("Generate Strong Random Password",style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold
),),
],
),
SizedBox(height: 15,),
TextFormField(
controller: _controller,
readOnly: true,
enableInteractiveSelection: false,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.cyan,),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.cyan),
),
suffixIcon: IconButton(
onPressed: (){
final data = ClipboardData(text: _controller.text);
Clipboard.setData(data);

final snackbar = SnackBar(
content: Text("Password Copy"));

ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(snackbar);
},
icon: Icon(Icons.copy))
),
),
SizedBox(height: 15,),
buildButtonWidget()
],
),

),
);

Widget buildButtonWidget() {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.black
),
onPressed: (){
final password = generatePassword();
_controller.text = password;
},
child: Text("Password Generate",style: TextStyle(color: Colors.white),)
);
}

}

Conclusion:

In the article, I have explained the Generate Strong Random Password of the basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Generate Strong Random Password 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 Generate Strong Random Password in your flutter projectsWe will show you what the Generate Random Password is?. Make a demo program for working Generate Strong Random Password and It displays When the user taps the button then, the password will generate with the combination of length, character, number, special, lower alphabet, and upper alphabet. It will generate on the text form field and the user also copies the generated password 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 Generate Strong Random Password Demo:

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


Explore Clean Architecture In Flutter
Clean architecture has been around for quite a while yet similarly as with all ‘best practice’ it’s get deciphered from…medium.com
Feel free to connect with us:
And read more articles from FlutterDevs.com.

From Our Parent Company Aeologic

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire 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.


Explore Clean Architecture In Flutter

0

Clean architecture has been around for quite a while yet similarly as with all ‘best practice’ it’s get deciphered from numerous points of view as there are software engineers. At its heart, Clean Architecture is an intricacy and change the management way to deal with getting sorted out code.

In this blog, we will be Explore Clean Architecture In Flutter. We will share a little about clean architecture in the flutter. I will talk in general about the concepts and how it works in your applications.

Table Of Contents::

Why Should Do We Need It?

Layers

The Basics Concept Of Clean Architecture

Dependencies

How Does This Help?

Conclusion



Why Should Do We Need It?:

On the off chance that you’ve been associated with programming in a business climate, it’s ensured you’ve seen a task start well and show a guarantee toward it. Possibly the code was composed well, the group applied unit testing, ran a tight agile ship, drove necessities through BDD, utilizing the very most current innovation, and inclined toward confided in wellsprings of figuring out how to “expertise up”.Or perhaps somebody has made a side venture that just ‘works’ and ought to be not difficult to stick underway.

Then, at that point possibly a couple of months in, or even weeks, the code begins to get somewhat abnormal. By one way or another making changes to the code gets increasingly hard. Merges get increasingly off-kilter and the capacity to remain Agile or Pivot to the client necessities begins to separate.

We’ve all seen it, and it happens each day in the product business. The causes can be complicated and complex however without a doubt the root cause is an absence of spotlight on architecture.

Layers:

Numerous types of architecture follow similar standards of layering. Isolating your code into a type of coordinated example of layers permits you to exchange those layers when required. Layering permits you to push innovation choices and execution subtleties out to the fringe of your application where they can be changed, modified or added depending on the situation without breaking your business rationale.

The fact of the matter is that picking one architecture and adhering to it’s anything but a vital component of staying away from specialized obligation or possibly having the option to address it as it develops. It ought to be clear at this point we will go over Clean Architecture, however, this article isn’t to say it’s awesome that others aren’t legitimate.

We will see how picking an architecture and folding your picked innovation over it allows you to convey quicker, with fewer headaches, and stay hyper-agile to client needs.

The Basics Concept Of Clean Architecture:

Clean Architecture was instituted by Robert Martin, broadly called ‘UncleBob’. Bob has various crucial books on coding throughout the long term, yet he is most popular for his considerations on ‘Clean’ code.

=> Entities layer

  • The items that are at the center of your business logic. Think Users, Locations, Books, and so forth. The fundamentals of OOP
  • The fundamental domain logic that your substances should follow. A User should have a name, a Location should have scope and longitude, and so forth

=> Use Case layer

  • The application logic of the framework. The Use Cases are the manners by which outside layers can utilize and interface with the entities
  • Add a user to the framework
  • Update a user’s location
  • Search for books of a similar type
  • This layer likewise contains the interface definitions for the repositories that will store the substances. The Use Cases acknowledge substantial executions of the interfaces, yet the executions DO NOT get made in this layer

=> Controllers/Presenters/Gateways layer: It is answerable for taking information and guidelines that are appropriate for the external layers and changing them over to those reasons for the Use Case layer. Basically planning between the outer layers and the Use Cases

=> Outer layer

  • These are the execution details of your application
  • Repository executions to work with your picked database innovation
  • The User Interface
  • Connections to other APIs and frameworks

Dependencies:

The key thing that makes this design (and others like it) so incredible toward conditions. Layers can just reference and work with different objects inside their own layer or lie inwards of their layer. This is a critical idea to comprehend as it drives every one of the advantages of decoupling and viability.

How about we draw an image! We will introduce a Clean way to deal with utilizing Google’s Flutter and Firebase stack. As we’ve referenced the advances don’t make any difference, you need to twist the innovations to your will and wrap them over a reasonable design!

Taking a genuinely clear task of joining users, logging them in, and allowing them to refresh their profile we can part the code across our Clean Architecture.

=> Entities: Straight forward User object, suppose there is some area logic in there which says the User should have a valid email address

=> Use Cases

  • Repository interfaces for Create, Retrieve and Update of Users
  • Use Cases containing the application logic
  • Signing up a New User
  • Logging in a new User
  • Retrieving a User Account
  • Updating a User’s details
  • These Use Cases have substantial repositories infused into their constructors meaning they only reference the repository interfaces
  • => Interface adapters
  • For this situation, we are utilizing BLoCs to be the parts that take the UI directions and information then, at that point convert them into Use Case activities
  • We’ve got a BLoC per UI ‘Page’ of Login and User Profile

=> Infrastructure

  • Contains the UI execution, in this model Flutter
  • Contains the Repository execution, here we are using Firebase
  • Objects in this layer do the Dependency Injection

How Does This Help?:

In case you’re still with me this far you likely could be thinking “wow that is a great deal of moving parts to just store an email in a DB” and you would be correct. All things considered, there are a few profound advantages to this methodology.

This methodology prepares in SOLID coding

  • Single Responsibility: It is advanced by making little lumps spread across the layers
  • Open-Close principle: It is advanced by keeping our business and application logic in our application. The nearer to the middle the components are the more outlandish they are to change and accordingly less open for adjustment
  • Liskov Substitution principle: It is advanced by having our interfaces characterized inside the area layers and the executions are made outside and infused inwards. This permits us to change the vault type utilized (Firebase to SQL for instance. There are more interfaces included regularly permitting further testing)
  • Dependency Inversion Principle: It sticks to layers can just allude to layers on a similar level or inwards of themselves. For instance, the Use Cases have the repository executions infused into them from the framework layer

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Clean Architecture In Flutter in your projectsWe will show you why should do we need it?. You have just learned the basic concept of clean architecture 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.