Google search engine
Home Blog Page 17

Implemented Overlay In Flutter

0

Whenever you will code for building anything in Flutter, it will be inside a widget. The focal intention is to build the application out of widgets. It portrays how your application view ought to look with its ongoing configuration and state. At the point when you made any adjustment in the code, the widget revamps its depiction by computing the contrast between the past and current widget to decide the negligible changes for delivering in the UI of the application.

Widgets are settled with one another to build the application. It implies the base of your application is itself a widget, and right down is a widget moreover. For instance, a widget can show something, can characterize design, can deal with collaboration, and so on.

In this post, we will explore the Implemented Overlay In Flutter. We will also implement a demo program of overlay, and to implement Overlay in Flutter we need to know about two Flutter built-in classes OverlayEntry class and the OverlayState class.

Table Of Contents::

Introduction

OverlayEntry

OverlayState

Code Implement

Code File

Conclusion



Introduction:

Overlays let independent child widgets “float” visual components on top of different widgets by embedding them into the overlay’s stack. The overlay gives every one of these widgets dealing with their support access to the overlay utilizing OverlayEntry objects.

The Overlay widget utilizes a custom stack execution, which is the same as the Stack widget. The primary use instance of Overlay is connected with the route and has the option to embed widgets on top of the pages in an application. To just show a pile of widgets, think about utilizing Stack all things considered.

Demo Module ::

The above demo video shows how to implement an overlay in a flutter and shows how the overlay will work using the OverlayEntry & OverlayState in your flutter applications. We will show a user when clicking on the button and then, show a different three container box with text and remove it according to delay of seconds. It will be shown on your device.

OverlayEntry:

A place in an Overlay that can contain a widget. Overlay entries are embedded into an Overlay utilizing the OverlayState.insert or OverlayState.insertAll functions. To find the nearest encasing overlay for a given BuildContext, utilize the Overlay. of function.

An overlay section can be in all things considered each overlay in turn. To remove an entry from its overlay, call the remove function on the overlay entry. Since an Overlay utilizes a Stack format, overlay sections can utilize Positioned and AnimatedPositioned to situate themselves inside the overlay.

> OverlayEntry Construction:

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

OverlayEntry({
required this.builder,
bool opaque = false,
bool maintainState = false,
})

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

> OverlayEntry Properties:

There are some parameters of OverlayEntry are:

  • > builder: This property is utilized for this entry and will incorporate the widget built by this builder in the overlay of the entry’s situation.
  • > opaque: This property is utilized to take a bool value that chooses whether this entry impedes the whole overlay. On the off chance that an entry professes to be opaque, for proficiency, the overlay will skip building entries underneath that entry except if they have a maintainState set.
  • > maintainState: This property is utilized to take bool value and if set true, it strongly builds the blocked entries under an opaque entry.

> OverlayEntry Methods:

There are only one methods of OverlayEntry are:

  • > remove: This method is used to remove this entry from the overlay.

OverlayState:

The current state of an Overlay is used to insert OverlayEntries into the overlay.

> OverlayState Methods:

There are some method of OverlayState are:

  • > debugIsVisibleThis method is utilized to check regardless of whether the given OverlayEntry is visible and returns a bool.
  • > insertThis method is utilized to embed the given OverlayEntry into the Overlay.
  • > insertAllThis method is utilized to take a List of OverlayEntries and embeds every one of the entries into the Overlay. You can likewise determine the above-mentioned and underneath properties to state in which request entries are to be embedded.
  • > rearrangeThis method is utilized to remove every one of the entries listed in the given List of OverlayEntries, then reinsert them into the overlay in the given order.

Code Implement:

You need to implement it in your code respectively:

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

In the main. dart file. Inside, we will create an OverlayDemo() class. In this class, we will create a Column widget. In this widget, we will add crossAxisAlignment and mainAxisAlignment as the center. Also, Add an image and Material Button(). In this button, we will add color, height, width, and the onPressed() method. In this method, we will add _showOverlay(context) Function. We will deeply describe it below later. Also, we will add the Text ‘show Overlay’.

Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/logo.png',height: 300,width: 350,),
const SizedBox(height: 50,),
MaterialButton(
color: Colors.pink[300],
minWidth: MediaQuery.of(context).size.width * 0.4,
height: MediaQuery.of(context).size.height * 0.06,
child: const Text(
'show Overlay',
style: TextStyle(color: Colors.white,fontSize: 17),
),
onPressed: () {
//calling the _showOverlay method
// when Button is pressed
_showOverlay(context);
},
),
],
)

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

Output

Now, we will deeply describe _showOverlay(context) Function:

First, we will be Declaring and Initializing OverlayState and
 OverlayEntry objects.

OverlayState? overlayState = Overlay.of(context);
OverlayEntry overlay1;
OverlayEntry overlay2;
OverlayEntry overlay3;

Then, we will create overlay1 that is equal to the theOverlayEntry(). We can return any widget we like here to be displayed on the Overlay. We will return Positioned widget with ClipRRect and inside add a container with height, width, and color. Its child, we will add Material with color and text.

overlay1 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.3,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.orange.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('The Flutter app developers at FlutterDevs have',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

Same as above for overlay2. The change was the color of the container and text on the Material widget. All the process was the same.

overlay2 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.5,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.pink.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('decades of industry experience under a single roof,',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

Same as above for overlay3. The change was the color of the container and text on the Material widget. All the process was the same. User can add any return widget you like here to be displayed on the Overlay.

overlay3 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.7,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.blue.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('and this empowers us to serve you with excellence.',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

After the instatement of OverlayEntries I have called the insertAll technique for OverlayState and passed it to the List of OverlayEntries, this adds every one of the Entries to the Overlay.

overlayState?.insertAll([overlay1, overlay2, overlay3]);

From that point forward, I have awaited on Future. delayed to make a delay of 2 seconds and afterward called remove strategy to remove the first OverlayEntry from the Overlay and afterward correspondingly I have delayed for one second then called remove for the second OverlayEntry and afterward again postponed for 1seconds and called remove for the third and last OverlayEntry, this causes the OverlayEntries to disappear one after another.

await Future.delayed(const Duration(seconds: 2));
overlay1.remove();

await Future.delayed(const Duration(seconds: 1));
overlay2.remove();

await Future.delayed(const Duration(seconds: 1));
overlay3.remove();

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

Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_overlay_demo/splash_screen.dart';

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.cyan,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

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

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

class _OverlayDemoState extends State<OverlayDemo> {
void _showOverlay(BuildContext context) async {
OverlayState? overlayState = Overlay.of(context);
OverlayEntry overlay1;
OverlayEntry overlay2;
OverlayEntry overlay3;
overlay1 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.3,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.orange.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('The Flutter app developers at FlutterDevs have',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});
overlay2 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.5,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.pink.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('decades of industry experience under a single roof,',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});
overlay3 = OverlayEntry(builder: (context) {
return Positioned(
left: MediaQuery.of(context).size.width * 0.1,
top: MediaQuery.of(context).size.height * 0.7,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.02),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.11,
color: Colors.blue.withOpacity(0.5),
child: Material(
color: Colors.transparent,
child: Text('and this empowers us to serve you with excellence.',
style: TextStyle(
fontSize: MediaQuery.of(context).size.height * 0.03,
//fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
);
});

overlayState?.insertAll([overlay1, overlay2, overlay3]);

await Future.delayed(const Duration(seconds: 2));

overlay1.remove();

await Future.delayed(const Duration(seconds: 1));

overlay2.remove();

await Future.delayed(const Duration(seconds: 1));

overlay3.remove();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[50],
appBar: AppBar(
title: const Text(
'Flutter Overlay Demo',
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
),
automaticallyImplyLeading: false,
centerTitle: true,
),
body: SafeArea(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/logo.png',
height: 300,
width: 350,
),
const SizedBox(
height: 50,
),
MaterialButton(
color: Colors.pink[300],
minWidth: MediaQuery.of(context).size.width * 0.4,
height: MediaQuery.of(context).size.height * 0.06,
child: const Text(
'show Overlay',
style: TextStyle(color: Colors.white, fontSize: 17),
),
onPressed: () {
_showOverlay(context);
},
),
],
))),
);
}
}

Conclusion:

In the article, I have explained the Overlay basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Overlay 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 Overlay in your flutter projectsWe will show you what the Introduction is?. What are the OverlayState and OverlayEntry, make a demo program for working Overlay using the OverlayEntry & OverlayState in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: SMS Using Twilio In Flutter


Flash Error Messages In Flutter

0

Flutter is a UI tool compartment for making quick, gorgeous, natively compiled applications for mobile, web, and desktop with one programing language and single codebase. It is free and open-source. It was at first evolved by Google and is 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-ordered into JavaScript code.

In this article, we will explore the Flash Error Messages In Flutter. We will see how to implement a demo program. Learn how to create a different style of the flash error message, it is called a snack bar, and how it shows error, success, or any warning message to the user in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Conclusion



Introduction:

The below demo output shows how to create flash messages in flutter and shows how flash messages will work like a snack bar used in your flutter applications. We will show a user when clicking on the button and then, show a flash message with your styles, text, and design. It will be shown on your device.

Demo Module ::

Demo Output

Code Implement:

You need to implement it in your code respectively:

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

In the main. dart file. Inside, we will create a MyHomePage() class. In this class, we will add a Column widget. In this widget, we will add crossAxisAlignment, mainAxisAlignment was the center. Inside, we will add an image and ElevatedButton().

Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/logo.png',height: 300,width: 350,),
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
'This Username is not found! Please try again later')));
},
child: const Text('Show Flash Error Message')),
),
],
),

Inside ElevatedButton, we will add style and onPressed function. In this function, we will create a simple SnackBar() method. In this method, we will add content that is equal to the text ‘This Username is not found! Please try again later. Also, we will add the child method. In this method, we will add the text ‘Show Flash Error Message’.

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

Now, this time all are the same but only changes on SnackBar(). Inside the SnackBar(), we will add behavior is equal to the SnackBarBehavior.floating and content is equal to the Container widget. In this widget, we will add padding, height, and decoration box with the color blue and border-radius circular(15). In the child, we will add the text ‘This Username is not found! Please try again later.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar( SnackBar(
behavior: SnackBarBehavior.floating,
content: Container(
padding: const EdgeInsets.all(8),
height: 70,
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(15)),
),
child: const Center(
child: Text(
'This Username is not found! Please try again later'),
),
),

));
},
child: const Text('Show Flash Error Message')),

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

Last but not least, now this time we will other changes to SnackBar() on the ElevatedButton(). Inside, we will add a background color that was transparent, behavior is equal to the SnackBarBehavior.floating, elevation is 0 and content is equal to the Stack() widget. Inside the widget, we will add alignment in was center, clipBehavior was none. We will also add a Row widget. In this widget, we will add a Column. In this Column, we will add two text widgets.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.transparent,
behavior: SnackBarBehavior.floating,
elevation: 0,
content: Stack(
alignment: Alignment.center,
clipBehavior: Clip.none,
children: [
Container(
padding: const EdgeInsets.all(8),
height: 70,
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(15)),
),
child: Row(
children: [
const SizedBox(
width: 48,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
'Oops Error!',
style: TextStyle(
fontSize: 18, color: Colors.white),
),
Text(
'This Username is not found! Please try again later',
style: TextStyle(
fontSize: 14, color: Colors.white),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
),
Positioned(
bottom: 25,
left: 20,
child: ClipRRect(
child: Stack(
children: [
Icon(
Icons.circle,
color: Colors.red.shade200,
size: 17,
)
],
),
)),
Positioned(
top: -20,
left: 5,
child: Stack(
alignment: Alignment.center,
children: [
Container(
height: 30,
width: 30,
decoration: const BoxDecoration(
color: Colors.red,
borderRadius:
BorderRadius.all(Radius.circular(15)),
),
),
const Positioned(
top: 5,
child: Icon(
Icons.clear_outlined,
color: Colors.white,
size: 20,
))
],
)),
],
),
));
},
child: const Text('Show Flash Error Message')),

Then, we will add a Positioned widget. In this widget, we will add the bottom is 25, and the left is 20. In this child, we will add ClipRRect, and inside we will add a circle icon. Also, we will create one more Positioned widget. In this widget, we will add a clear icon.

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


Conclusion:

In the article, I have explained the Flash Error Messages basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Flash Error Messages 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 Flash Error Messages in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working Flash Error Messages in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter


Exploring Dart Constructors

0

In this blog, we will be Exploring Dart Constructors. Client befuddled by that puzzling linguistic structure in Dart constructors? Colons, named boundaries, asserts, etc. We’ll track down constructors on this blog.



What is Constructor?:

A constructor is an exceptional strategy that is utilized to introduce objects. The constructor is called when an object of a class is made.

In object-oriented programming when an object is made, it is naturally called the constructor. All classes have their default constructor which is made by the compiler when the class is called, besides one can likewise characterize its very own constructor. Yet, you should take note that if you do such, the default constructor won’t be made and will be overlooked.


When we need an example of a specific class we call a constructor, isn’t that so?

var animal = new Animal();

In Dart 2 we can leave out the new:

var animal = Animal();

A constructor is utilized to guarantee instances are made in a reasonable state. This is the definition in a class:

class Animal {
Animal();
}

Initializing:

Most times we want to design our cases. For instance, pass in the height of an animal:

var a = Animal(7);

a is now a 7-feet tall Animal.

To compose that constructor we incorporate the height field after the colon :

class Animal {
double height;
Animal(height) : this.height = height;
}

This is called an initializer. It acknowledges a comma-isolated rundown of articulations that initialize fields with contentions.

Luckily, Dart gives us an easy route. If the field name and type are equivalent to the argument in the constructor, we can do the:

class Animal {
double height;
Animal(this.height);
}

At times we should call super constructors while initializing:

class Age {
String name;
Age(this.name);
}

class Animal extends Age {
static mToFt(m) => m * 5.100;
double height;
Animal(height, name) : this.height = mToFt(height), super(name);
}

Notice that super(...)should constantly be the last bring in the initializer.

Furthermore, on the off chance that we expected to add more mind-boggling monitors (than types) against a twisted animal, we can utilize assert:

class Animal {
final double height;
Animal(height) : this.height = height, assert(height > 3.0);
}

Accessors and mutators:

Back to our earlier animal definition:

class Animal {
double height;
Animal(this.height);
}

void main() {
var a = Animal(7);
print a.height); // 7
}

How about we keep anybody from changing the height by making the field private.

In Dart, there is no private keyword. All things considered, we utilize a show: field names beginning with _ are private.

class Animal {
double _height;
Animal(this._height);
}

Amazing! Yet, presently it is impossible to get to a.height. We can make the height property read simply by adding a getter:

class Animal {
double _height;
Robot(this._height);

get height {
return this._height;
}
}

Getters are capacities that take no contentions and adjust to the uniform access principle.

We can rearrange our getter by utilizing two alternate ways: single expression syntax and implicit this:

class Animal {
double _height;
Robot(this._height);

get height => _height;
}

We can consider public fields as private fields with getters and setters as the same. That is:

class Animal {
double _height;
Animal(this._height);

get height => _height;
set height(value) => _height = value;
}

Remember initializers just assign values to fields and it is in this manner impractical to utilize a setter in an initializer:

class Animal {
double _height;
Animal(this.height); // ERROR: 'height' isn't a field in the enclosing class

get height => _height;
set height(value) => _height = value;
}

Constructor bodies:

If a setter should be called, we’ll need to do that in a constructor body:

class Animal {
double _height;

Animal(h) {
height = h;
}

get height => _height;
set height(value) => _height = value;
}

We can do a wide range of things in constructor bodies, yet we can’t return a value!

class Animal {
double height;
Animal(this.height) {
return this; // ERROR: Constructors can't return values
}
}

Final fields:

Final fields will be fields that must be relegated once.

final a = Animal(7);
a = Animal(9); /* ERROR */

Inside our class, we won’t be able to use the setter:

class Animal {
final double _height;
Animal(this._height);

get height => _height;
set height(value) => _height = value; // ERROR
}

Just like with var, we can utilized final before any type of definition:

var a;
var Animal a;


final a;
final Animal a;

The accompanying won’t work since height, being final, should be instated. What’s more, initialization occurs before the constructor body is run. How about we fix it:

class Animal {
final double height;
Animal(this.height);
}

Default values:

On the off chance that most animals are 7-feet tall, we can try not to indicate the height each time. We can suggest argument optional and give a default value:

class Animal {
final double height;
Animal([this.height = 7]);
}

So we can just call:

void main() {
var a = Animal();
print(a.height); // 7

var a2d2 = Animal(5.100);
print(a2d2.height); // 5.100
}

Immutable animals:

Our animals have more attributes than a height. Let’s add some more!

class Animal {
final double height;
final double weight;
final String name;

Animal(this.height, this.weight, this.name);
}

void main() {
final a = Animal(7, 150, "Whale");
a.name = "Fish"; // ERROR
}

As all fields are final, our animals are immutable! Once they are initialized, their attributes can’t be changed.

We can solve this with a const constructor:

class Animal{
final double height;
final double weight;
final List<String> names;

const Animal(this.height, this.weight, this.names);
}

void main() {
final a = const Robot(5, 170, ["Whale"]);
printar.names..add("Fish")); // ERROR: Unsupported operation: add
}

const must be utilized with articulations that can be processed at compile time. Take the accompanying model:

import 'dart:math';

class Animal {
final double height;
final double weight;
final List<String> names;

const Animal(this.height, this.weight, this.names);
}

void main() {
final a = const Animal(5, 170, ["Whale", Random().nextDouble().toString()]); // ERROR: Invalid constant value
}

const occurrences are canonicalized which implies that equivalent occasions highlight a similar item in memory space while running. Also, indeed, involving const constructors can further develop execution in Flutter applications.

Named Constructors:

In addition to the fact that arguments be can be named. We can give names to quite a few constructors:

class Animal {
final double height;
Animal(this.height);

Animal.fromWater(String water) : height = (water == 'whale') ? 5: 8;
Animal.copy(Animal other) : this(other.height);
}

void main() {
print(Animal.copy(Animal(7)).height); // 7
print(new Animal.fromWater('whale').height); // 5
print(new Animal.fromWater('crocodile').height); // 8
}

What occurred in duplicate? We utilized this to call the default constructor, actually “diverting” the launch.

Invoking named super constructors work as expected:

class Age{
String name;
Age();
Age.named(this.name);
}

class Animal extends Age {
final double height;
Animal(this.height);

Animal.named({ height, name }) : this.height = height, super.named(name);
}

void main() {
print(Animal.named(height: 8, name: "Whale").name); // Whale
}

Note that named constructors require an anonymous constructor to be characterized!

Private Named Constructors:

Be that as it may, imagine a scenario where we would have rather not uncovered a public constructor. Just named?. We can make a constructor private by prefixing it with an underscore:

class Robot {
Robot._();
}

Applying this information to our past model:

class Age {
String name;
Age._();
Age.named(this.name);
}

class Animal extends Age {
final double height;
Animal._(this.height, name) : super.named(name);

Animal.named({ height, name }) : this._(height, name);
}

void main() {
print(Animal.named(height: 8, name: "Whale").name); // Whale
}

The named constructor is “diverting” to the private default constructor. Purchasers of this API just see Animal.named() it as a method to get animal instances.

Factory Constructor:

We said constructors were not permitted to return. Prepare to be blown away. Factory constructors can!

class Animal {
final double height;

Animal._(this.height);

factory Animal() {
return Animal._(8);
}
}

void main() {
print(Animal().height); // 7
}

Factory constructors are syntactic sugar for the “factory pattern”, typically carried out with static capacities.

They seem like a constructor from an external perspective, yet inside they can designate occurrence creation by invoking a “normal” constructor. This makes sense why factory constructors don’t have initializers.

Since factory constructors can return different examples, we can do extremely helpful things like:

  • > caching: conditionally returning existing objects.
  • > subclasses: returning other instances such as subclasses.
class Animal {
final double height;

static final _cache = <double, Robot>{};

Animal._(this.height);

factory Animal(height) {
return _cache[height] ??= Animal._(height);
}
}

void main() {
final r1 = Animal(8);
final r2 = Animal(8);
final r3 = Animal(10);

print(r1.height); // 8
print(r2.height); // 8
print(identical(r1, r2)); // true
print(r3.height); // 10
print(identical(r2, r3)); // false
}

Singletons:

Singletons are classes that just at any point make one occurrence. We consider this a particular instance of caching!.

Let’s implement the singleton pattern in Dart:

class Animal {
static final Animal _instance = new Animal._(7);
final double height;

factory Animal() {
return _instance;
}

Animal._(this.height);
}

void main() {
var r1 = Animal();
var r2 = Animal();
print(identical(r1, r2)); // true
print(r1 == r2); // true
}

The factory constructor Animal(height)just consistently returns the unrivaled occurrence that was made while stacking the Animal class.

Conclusion:

In the article, I have explained the Dart constructors. This was a whole introduction to Dart constructors On User Interaction from my side, and it’s working using Dart.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: Exploring Dart DevTools

Related: Exploring Inheritance and Composition in Dart & Flutter


Explore AnimatedDefaultTextStyle In Flutter

0

Adding an Animation to a Flutter Mobile Application is a significant piece of an App Development Process. Consider the possibility that we need to enliven the text in a Flutter Mobile Application.

Animations expect a colossal part in updating your application’s general client experience from the visual examination, movement, and up to the custom animations, you can truly envision!. Like a few distinct things facilitated into an application, animations should be useful instead of essentially an ordinary elaborate organization.

In this post, we will Explore AnimatedDefaultTextStyle In Flutter. We will also implement a demo program of animated default text style, and show text animations as well as images also in your flutter applications.

AnimatedDefaultTextStyle class – widgets library – Dart API
Animated version of DefaultTextStyle which automatically transitions the default text style (the text style to apply to…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Parameters

Code Implement

Code File

Conclusion



Introduction:

Quickening text in Flutter is utilized. It is an Animated Adaptation of the DefaultTextStyle widget. AnimatedDefaultTextStyle widget automatically transitions the default text style over a given duration at whatever point the given style changes.

Demo Module ::

The above demo video shows how to implement an AnimatedDefaultTextStyle in flutter and shows how AnimatedDefaultTextStyle will work in your flutter applications. We will show a user when clicking on the button and then, show a text and image size will be animated and the size was increased/decrease. It will be shown on your device.

Construction:

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

const AnimatedDefaultTextStyle({
Key? key,
required this.child,
required this.style,
this.textAlign,
this.softWrap = true,
this.overflow = TextOverflow.clip,
this.maxLines,
this.textWidthBasis = TextWidthBasis.parent,
this.textHeightBehavior,
Curve curve = Curves.linear,
required Duration duration,
VoidCallback? onEnd,
})

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

Properties:

There are some parameters of AnimatedDefaultTextStyle are:

  • > child — This property is used to the widget can only have one child. To layout multiple children, let this widget’s child be a widget such as Row, Column, or Stack, which have a children property, and then provide the children with that widget.
  • > curve — This property is used to the curve to apply when animating the parameters of this container.
  • > style — This property is used for the target text style. The text style must not be null. When this property is changed, the style will be animated over [duration] time
  • > duration — This property is used for the duration over which to animate the parameters of this container. It represents a difference from one point in time to another.
  • > onEnd() — This property is used to call every time an animation completes. This can be useful to trigger additional actions e.g. another animation at the end of the current animation.
  • > overflow — This property is used to how visual overflow should be handled. This property takes effect immediately when changed, it is not animated.

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we will create some variables like a bool _first is equal to true, double _fontSize is equal to 40, Color _color is equal to cyan color, and double _height is equal to 100.

bool _first = true;
double _fontSize = 40;
Color _color = Colors.cyan;
double _height = 100;

In the body, we will add a SizeBox widget with height. Inside the widget, we will add AnimatedDefaultTextStyle() widget. In this widget, we will add curve was bounceOut, add duration was milliseconds. Also, we will add style property. In this property, we will add the fontSize variable and color variable. In the child, we will add the Column widget. In this widget, we will add images and text “Flutter Dev”.

SizedBox(
height: 210,
child: AnimatedDefaultTextStyle(
curve: Curves.bounceOut,
duration: const Duration(milliseconds: 350),
style: TextStyle(
fontSize: _fontSize,
color: _color,
fontWeight: FontWeight.bold,
),
child: Column(
children: [
Image.asset(
'assets/logo.png',
height: _height,
width: 280,
),
const SizedBox(
height: 10,
),
const Text("Flutter Dev's"),
],
),
),
),

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

Output

Now, we will create an ElevatedButton(). In this button, we will add the onPressed method. In this method, we will add setState() function. In this function, we will add the _fontSize variable is equal to the _first variable then size is 60 else 40, add the _color variable is equal to the _first variable then color is blue else brown. In the child, we will add the text “Click Here!!”.

SizedBox(
height: 50,
width: 150,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
textStyle: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
onPressed: () {
setState(() {
_fontSize = _first ? 60 : 40;
_color = _first ? Colors.blue : Colors.brown;
_first = !_first;
_height = _first ? 100 : 130;
});
},
child: const Text(
"Click Here!!",
),
),
)

When the user presses the button then, the text will be animated, and change the size and color also, and the image size also changes. It will be shown on your screen devices.

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_animated_default_text_style/splash_screen.dart';

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

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

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

class _MyHomePageState extends State<MyHomePage> {
bool _first = true;
double _fontSize = 40;
Color _color = Colors.cyan;
double _height = 100;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter AnimatedDefaultTextStyle Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.cyan,
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
height: 210,
child: AnimatedDefaultTextStyle(
curve: Curves.bounceOut,
duration: const Duration(milliseconds: 350),
style: TextStyle(
fontSize: _fontSize,
color: _color,
fontWeight: FontWeight.bold,
),
child: Column(
children: [
Image.asset(
'assets/logo.png',
height: _height,
width: 280,
),
const SizedBox(
height: 10,
),
const Text("Flutter Dev's"),
],
),
),
),
const SizedBox(
height: 20,
),
SizedBox(
height: 50,
width: 150,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.cyan,
textStyle: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
onPressed: () {
setState(() {
_fontSize = _first ? 60 : 40;
_color = _first ? Colors.blue : Colors.brown;
_first = !_first;
_height = _first ? 100 : 130;
});
},
child: const Text(
"Click Here!!",
),
),
)
],
),
),
);
}
}

Conclusion:

In the article, I have explained the AnimatedDefaultTextStyle basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to AnimatedDefaultTextStyle 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 AnimatedDefaultTextStyle in your flutter projectsWe will show you what the Introduction is?. Some AnimatedDefaultTextStyle properties, make a demo program for working AnimatedDefaultTextStyle. It shows text will be animated, and change the size and color also, and the image size also changes 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.


Drop Shadow Effect In Flutter

0

Some of the time you want to apply a shadow effect on your application. How should you have such an effect if you’re using Flutter?. A plugin called DropShadow is proper hence. DropShadow is a plugin that applies a picture as well as a widget moreover.

In this blog, we will explore Drop Shadow Effect In Flutter. We will see how to implement a demo program of the drop shadow and how to use the Drop Shadow effect for any widget using the drop_shadow package in your flutter applications.

drop_shadow | Flutter Package
It’s a drop shadow effect not only for images but also for any widget in Flutter.pub.dev

Table Of Contents::

Introduction

Constructor

Parameters

Implementation

Code Implement

Code File

Conclusion



Introduction:

Drop Shadow effect for any image as well as any widget also. The below demo screenshot shows how to use a drop shadow in a flutter. It shows how the drop shadow will work using the drop_shadow package in your flutter applications. It shows a shadow effect on the networking image, assets image, container widget, and text widget. It will be shown on your device.

Demo Module :

Constructor:

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

const DropShadow({
Key? key,
required this.child,
this.blurRadius = 10.0,
this.borderRadius = 0.0,
this.offset = const Offset(0.0, 8.0),
this.opacity = 1.0,
this.spread = 1.0,
})

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

Parameters:

There are some parameters of DropShadow are:

  • > child — This parameter is used to the widget can only have one child. To layout multiple children, let this widget’s child be a widget such as Row, Column, or Stack, which have a children property, and then provide the children with that widget.
  • > blurRadius — This parameter is used to the blur size of the shadow (default: 10.0).
  • > borderRadius —This parameter is used to the BorderRadius to the image and the shadow (default: 0.0).
  • > offset — This parameter is used to the position of the shadow (default: Offset(0.0, 8.0)).
  • > opacity — This parameter is used to the given opacity to the shadow (default: 1.0).
  • > spread — This parameter is used for the size of the shadow (default: 1.0).

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
drop_shadow: ^0.0.1+4

Step 2: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

Step 3: Import

import 'package:drop_shadow/drop_shadow.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the main.dart file, we will create a HomePage() class. In this class, we will make some DropShadow demo. First, we will create a network image and wrap it in the DropShadow() widget. Inside the widget, we add default blurRadius, add Offset(3, 3), and the size of the shadow.

DropShadow(
blurRadius: 10,
offset: const Offset(3, 3),
spread: 1,
child: Image.network(
'https://images.unsplash.com/photo-1651794327243-d976672943c2?crop=entropy&cs=tinysrgb&fm='
'jpg&ixlib=rb-1.2.1&q=80&raw_url=true&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto='
'format&fit=crop&w=1974',
width: 280,
),
),

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

Network Image Output (Drop Shadow Effect)

Next, we will add the DropShadow() widget. In this widget, we will add an assets image from the assets folder with height and width. Drop Shadow gives a shadow effect on this image.

DropShadow(
child: Image.asset('assets/logo.png',height: 140,
width: 280,),
),

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

Assets Image Output (Drop Shadow Effect)

Now, we will create a Container widget. In this widget, we will add the height and width of the container. Also, add border-radius and gradient colors in the BoxDecoration. The whole widget is wrapped into its DropShadow() widget.

DropShadow(
child: Container(
height: 145,
width: 280,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: const LinearGradient(
colors: [Color(0xFFEC3DEC), Color(0xFF73C5ED)],
),
),
),
),

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

Container Widget Output (Drop Shadow Effect)

Last but not least, we will a text “Flutter Devs” and wrap it to it DropShadow() widget. They give a shadow effect on a text also.

const DropShadow(
child: Text(
"Flutter Dev's",
style: TextStyle(fontSize: 40, fontWeight:FontWeight.bold,color: Colors.cyan),
),
),

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

Text Output (Drop Shadow Effect)

Code File:

import 'package:drop_shadow/drop_shadow.dart';
import 'package:flutter/material.dart';
import 'package:flutter_drop_shadow_demo/splash_screen.dart';

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

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

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

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

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Drop Shadow Effect Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.teal,
),
body: Center(
child: SingleChildScrollView(
child: Column(
children: [
DropShadow(
blurRadius: 10,
offset: const Offset(3, 3),
spread: 1,
child: Image.network(
'https://images.unsplash.com/photo-1651794327243-d976672943c2?crop=entropy&cs=tinysrgb&fm='
'jpg&ixlib=rb-1.2.1&q=80&raw_url=true&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto='
'format&fit=crop&w=1974',
width: 280,
),
),
DropShadow(
child: Image.asset('assets/logo.png',height: 140,
width: 280,),
),
DropShadow(
child: Container(
height: 145,
width: 280,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: const LinearGradient(
colors: [Color(0xFFEC3DEC), Color(0xFF73C5ED)],
),
),
),
),
const DropShadow(
child: Text(
"Flutter Dev's",
style: TextStyle(fontSize: 40, fontWeight:FontWeight.bold,color: Colors.cyan),
),
),
],
),
),
),
);
}
}

Conclusion:

In the article, I have explained the Drop Shadow Effect’s basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Drop Shadow 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 Drop Shadow Effect in your flutter projectsWe will show you what the Introduction is?. Some drop shadow effect parameters, make a demo program for working Drop Shadow Effect. The Drop Shadow effect for any widget or any image using the drop_shadow package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: Dark Mode Implementation

Related: Handling Navigation Stacks


Flutter 3.0— What’s New In Flutter

0

Last year in Google I/O, the Flutter group declared Flutter 2.2. From that point forward, there have been a couple of huge upgrades and stable releases to Flutter. It shows how incredible Flutter is performing and the way responsive its group is to resolve basic issues, update Flutter, and take it to a higher level.

In this article, we will explore the Flutter 3.0 — What’s New In Flutter. Flutter 3.0 is live and prepared for creation on all desktop stages! We are invigorated and can hardly stand by to share what’s new in Flutter, its support for macOS and Linux, the remarkable performance upgrades for web and mobile, and adding support for Apple Silicon.



Introduction:

Flutter is essentially intended to be portable and ready to make delightful applications. Flutter developer tooling centers around making our development process quick and productive.

It has just been three months since Flutter declared its support for Windows, and we are right here, practically amidst May, with the most recent Flutter update. This all-new version is stable for macOS and Linux and supports Apple Silicon. The version update from Flutter 2 to Flutter 3 scaffolds the excursion from a mobile-centric to a multi-platform framework.https://www.youtube.com/embed/YRuQj7mlH2I?feature=oembed

Flutter is currently an undisputed and most well-known cross multi-stage UI tool stash for making natively compiled applications. The best thing about Flutter is that it is something other than a Google product, and everybody can taste its cut of achievement. Anybody can release the force of this open-source stage either through contributing code, building packages supporting the core system, composing material and instructional tutorials, and numerous alternate ways.

Flutter 2 Vs Flutter 3:

The Flutter 3 delivery supports macOS for Universal Binaries so that Flutter applications can work natively on Apple Silicon chips and Intel. Google has teamed up with Ubuntu’s Canonical for the Linux delivery to convey a profoundly incorporated cream of the cream choice for application development.

We should dive into what’s new in Flutter 3.0 to find every one of the significant elements of Flutter’s steady release.

macOS & Linux are finally stable!:

Windows, Web, Android, and iOS have been stable for some time, lastly, we can invite macOS and Linux to the rundown of stable support. Flutter 3 is one of the main achievements in the journey of Flutter up to now since Flutter 3.0 supports all the six platforms on the stable channel formally.

Menu Cascading and Support for the MacOS System Menu Bar:

The new Flutter 3 highlights contain new contributions for platform-specific integration, intuitive models for compilation to build support, give accessibility, and internationalization.

The purpose of the update is to offer adaptability to use the operating system and share ideal UI and rationale according to prerequisites. The Flutter’s most recent highlights take special care of platform support past rendering pixels.

Cascading menus demo

Flutter 3 presently supports the Apple Silicon Mac. Look at the new macOS install page to utilize the Apple Silicon download button.

Material 3:

Indeed, one of the top features of what’s happening in the Flutter 3.0 conversation is the change to Material Design 3, a Google in-house design language. The Flutter group has offered a versatile cross-stage design framework to change your Flutter application into a lovely intuitive product.

Material 3 (otherwise called Material You) is the up-and-coming age of Material Design. The massive changes incorporate a variety of framework enhancements, typography upgrades, and updates for many components.

The Material 3 widgets in Flutter were presented with highlights including

  • > Adaptive colors
  • > New buttons
  • > New app menu
  • > Variable font support

How you really want to involve Material 3 in Flutter 3.0 is to empower it by means of a boundary to ThemeData

return MaterialApp(   
theme: ThemeData(useMaterial3: true),
// ... );

Flutter Firebase:

The application distributers require a complete arrangement of tools to help you in operating, assembling, and releasing your Flutter applications. These incorporate administrations, for example, data storage, validation, authentication, device testing, and cloud functions. Flutter hosts different third-party-together mixes like Firebase, AWS Amplify, Sentry, and AppWrite. Firebase is Google’s back-end stage for building mobile and web applications.

The team at Flutter has declared the Flutter Firebase integration empowering a completely upheld core part of the Firebase offering. As indicated by the report from Slashdata, 62% of Flutter developers use Firebase for their Flutter applications.

• > Firebase Crashlytics:

You can now track real-time fatal mistakes utilizing the Flutter Crashlytics plugin, with a similar arrangement of elements through Firebase’s popular real-time crash reporting administration. The elements incorporate basic alarming measurements like “crash-free users” that help you in staying aware of the steadiness of your application.

It is currently simple to triage, focus on and fix issues utilizing the Crashlytics pipeline, which has been moved up to upgrade the bunching of Flutter crashes.

Flutter’s Games Toolkit:

The Flutter group has focussed on casual gamers this time to deliver a simple to-utilize easygoing games tool stash. It offers a starter pack of formats and acknowledges for advertisements as well as cloud services.

Note: The developers at Flutter have made a pleasant pinball game controlled by Firebase and Flutter’s web support which shows the flexibility of the new Flutter 3 update. You can develop games on Flutter through this Games doc page.

Mobile Updates:

Android and iOS were the main stages all along, and in Flutter 3, they have gotten a couple of significant upgrades.

  • > Foldable support for phones: What’s going on in Flutter 3? Indeed, the all-new Flutter discharge integrates foldable cell phones. New widgets and highlights permit you to build dynamic and engaging encounters for the eye on foldable devices. This element is planned as a team with Microsoft.
  • > Variable refresh rate support for IOS: The new Flutter version upholds variable refresh rates and ProMotion shows on iOS devices, including iPad Pro and iPhone 13 Pro. The delivering ability is currently at refresh rates up to 120 Hz, which was restricted to 60 Hz previously. The user can have a smoother looking-over experience while observing quick animations.

Flutter Web Updates:

Flutter web has not gotten many redesigns in this version. Notwithstanding, there are a couple of huge upgrades, particularly for performance.

  • > Image decoding: The most recent Flutter 3 version contains new APIs to non concurrently unravel pictures off the fundamental string. This is done through the underlying picture codecs of the program. You would be glad to realize that this element speeds up decoding the image 2x, guaranteeing that the fundamental string is rarely impeded and clearing the junk built-up in the previously.
  • > Web app lifecycles: The new web application lifecycle API for Flutter applications gives you the advantage of controlling the cycle for bootstrapping your application. This allows you to run the Flutter in headless mode on the web. This applies to many use-cases, including the accompanying oftentimes mentioned situations:

A splash screen.

A loading indicator.

A plain HTML interactive landing page is displayed before the Flutter app.

You can now leverage the desktop support for your app.

Flutter DevTools:

Flutter DevTools is an incredible expansion to Flutter that assists with troubleshooting any Flutter application as useful as could really be expected. There are a couple of updates in Flutter DevTools 2.12.2

  • > Enhance Tracing under the performance tab
  • > Improvement on the Network tab
  • > Dedicated plugin for Provider to keep track of change notifier

Flutter 3.0 Performance Improvements:

The developer’s group at Flutter has taken the Flutter performance improvement to a higher level by benchmarking to assess the streamlining benefits. Above all, the mistiness movement execution has been improved for straightforward case situations.

For example, when an Opacity widget comprises a solitary rendering primitive, the saveLayer technique is overlooked and is typically summoned by Opacity.

The Flutter 3 delivery presents a component that predicts and appraises the delivering picture intricacy given the drawing operations cost that it contains. This is utilized as a way to deal with diminished memory utilization without a relapse in Flutter application execution.

More Exciting Features:

Here are a few additional reports on the Flutter ecosystem carefully chosen solely for you!

> Theme Extensions:

You can now add anything to the ThemeData of the material library utilizing Theme extensions. Rather than expanding ThemeData and executing copyWith, lerp, and different strategies once more, you can specify ThemeData.extensions.

Additionally, as a package developer, you can give ThemeExtensions.

> Ads:

Flutter 3 supports the distributer’s prerequisites for making customized promotions and dealing with Apple’s App Tracking Transparency (ATTT) necessities. Google gives a User Messaging Platform (UMP) SDK that substitutes the past open-source Consent SDK.

Introducing Dart 2.17:

Dart 2.17 stable was declared alongside Flutter 3.0 with some hotly anticipated highlights that developers have been waiting for. Dart is the mystery ingredient behind Flutter, and any upgrades in Dart would assist with working on Flutter’s development. We should investigate the new highlights.

  • > Enhanced Enumerations:

A gigantic update has landed enum to super-charge them. We use influence extensions to broaden the usefulness of enums including characterizing techniques. Beginning from Dart 2.17, we never again need to utilize our more older model to work with the enum.

enum Bikes {
suzuki Hayabusa('Model X', 200);
bmw R('1250 GS', 120);
ducati Panigale V4('1103 cc', 220);

final String name;
final int price;

const Cars(this.name, this.price);

String get nameAndPrice => '$name:$price';

String greeting(String yourName) {
return 'My name is $yourName and I have a $name that costs $price!';
}

@override
String toString() {
return 'The name is $name and price is $price';
}
}

void main() {
print(Cars.suzuki Hayabusa.greeting('User'));
print(Cars.bmw R);
print(Cars.ducati Panigale V4.name);
}
  • > Super constructors:

This is maybe one of my top choices that will shorthand our coding, in which you might pass constructor arguments to the superclass.

We should explore what the new syntax resembles. We used to have the old syntax like beneath:

class User {

User(this.name);

final String name;

}

// Old way: before Dart 2.17

class Test extends User {

Test(String name, this.age) : super(name);

final int age;

}
  • > The new syntax is straightforward:
class User {

User(this.name);

final String name;

}

// New way: Dart 2.17 and above

class Test extends User {

Employee(super.name, this.age);

final int age;

}
  • > Name args anywhere:

Beforehand, we needed to add name arguments in the last position of the constructor. From Dart 2.17, we never again need to do that. You can put your named arguments anyplace in the constructor.

class User {

User(this.name);

final String name;

}

class Test extends User {

Test(super.name, {required this.age});

final int age;

void employee() => print('$name is $age year-old and is employee');

}

void main() {

Test(age: 26, 'User').employee();

}

Conclusion:

I have attempted to sum up and provide you with the best features of Flutter 3.0. In any case, I suggest watching the keynote and enjoying the incredible introductions and energizing interviews.

You can peruse Introducing Flutter 3 and Dart 2.17: Productivity and integration blogs for more data. It is irrefutable that the community merits all commendations for accomplishing this great work to assist Flutter with achieving the situation with glory and advancement to keep up with its type of aiding organizations of every kind across the world.

We want to believe that you have had an all-encompassing encounter perusing our blog post on What’s New In Flutter 3.0. The eventual fate of Flutter appears to be splendid and promising for building superb encounters in the application ecosystem.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter


Image Compress & Crop In Flutter

0

Working with the camera/gallery and involving it in various applications is very typical in applications yet while carrying out it you might deal with different issues -, for example, assuming you are working in an application that is fundamentally an e-commerce application where we really want to oversee various things we want to choose various things and furthermore post our reactions with pictures around then we should have to compose a single codebase from where we can oversee camera at various areas all through the application.

In this article, we will explore the Image Compress & Crop In Flutter. We will see how to implement a demo program. Learn how to image compress and crop using a camera & gallery in your flutter applications.

For Image Compress:

flutter_native_image | Flutter Package
Run this command: With Flutter: $ flutter pub add flutter_native_image This will add a line like this to your package’s…pub.dev

For Image Crop:

image_cropper | Flutter Package
A Flutter plugin for Android, iOS, and Web supports cropping images. This plugin is based on three different native… pubs.dev

For Image Picker:

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

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion

GitHub Link



Introduction:

The below demo video shows how to implement an image compress & crop in flutter and shows how image compress & crop will work using the camera and gallery in your flutter applications. We will show a user when clicking on the upload button and then, show a popup with a camera and gallery fields. When the user chooses any one option then the image will be compressed and then crop and It will be shown on your device.

Demo Module ::

Demo

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
image_picker: ^0.8.5
image_cropper: ^1.5.1
flutter_native_image: ^0.0.6+1

Step 2: Import

import 'package:image_picker/image_picker.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_cropper/image_cropper.dart'

Step 3: Add a few things to the AndriodManifest.xml file.

<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

We will create an AppHelper() class. In this class, we will create the static cropImage name file and add all data for the crop images. Yow will use it anywhere in our project.

static Future<File?> cropImage(File? imageFile) async {
var _croppedFile = await ImageCropper().cropImage(
sourcePath: imageFile!.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: const AndroidUiSettings(
toolbarColor: Color(0xFF2564AF),
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
);

return _croppedFile;
}

Also, we will create a static compress name file, and inside we will add a file image, quality, and percentage of an image. Yow will use it anywhere in our project.

static Future<File> compress({
required File image,
int quality = 100,
int percentage = 30,
}) async {
var path = await FlutterNativeImage.compressImage(image.absolute.path,
quality: quality, percentage: percentage);
return path;
}
}

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

First, we will create a final _picker that is equal to the ImagePicker(). Also, creating a File instance was fileImage.

final _picker = ImagePicker();
File? fileImage;

In the body, we will add the column. In this column widget, we will add a Container with height and width. Inside the Container, we will add a Column widget. In this widget, we will add images and text. When the user run code then shows this screen before adding any image.

Container(
height: 350,
width: 350,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(color: Colors.black12, width: 1),
borderRadius: const BorderRadius.all(Radius.circular(10)),
color: Colors.grey[300],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/logo.png",
width: 150,
),
const SizedBox(
height: 20,
),
const Text(
"Image will be shown here",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 20),
),
],
),
),

Also, create a ElevatedButton(). On this button, we will add the onPressed method. In this method, we will add _openChangeImageBottomSheet() function. This function we will describe later below. Also, add the text ‘Upload Image’.

ElevatedButton(
onPressed: () {
_openChangeImageBottomSheet();
},
child: const Text('Upload Image')),

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

Output

We will add create a container with height and width, alignment was center. Add the box decoration with border color, border-radius , color and DecorationImage(). Inside DecorationImage, we will add an image: FileImage(fileImage!). When a user uploads an image using compresses and crops an image from the camera and gallery.

Container(
height: 350,
width: 300,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(color: Colors.black12, width: 1),
borderRadius: const BorderRadius.all(Radius.circular(10)),
color: Colors.grey,
image: DecorationImage(
image: FileImage(fileImage!),
fit: BoxFit.cover,
)),
)

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

Output

Now, we will describe _openChangeImageBottomSheet() function:

We will create a showCupertinoModalPopup(). In this popup, we will return CupertinoActionSheet(). In this sheet, we will add the actions widget. In actions widget, we will add three _buildCupertinoActionSheetAction(). Inside we will add icons, titles, and the voidCallback function. In this function, we will add Navigator.pop(context) and _getImageFrom(source: ImageSource.gallery/camera). We will define the below later.

_openChangeImageBottomSheet() {
return showCupertinoModalPopup(
context: context,
barrierDismissible: false,
builder: (context) {
return CupertinoActionSheet(
title: Text(
'Change Image',
textAlign: TextAlign.center,
style: AppTextStyles.regular(fontSize: 19),
),
actions: <Widget>[
_buildCupertinoActionSheetAction(
icon: Icons.camera_alt,
title: 'Take Photo',
voidCallback: () {
Navigator.pop(context);
_getImageFrom(source: ImageSource.camera);
},
),
_buildCupertinoActionSheetAction(
icon: Icons.image,
title: 'Gallery',
voidCallback: () {
Navigator.pop(context);
_getImageFrom(source: ImageSource.gallery);
},
),
_buildCupertinoActionSheetAction(
title: 'Cancel',
color: Colors.red,
voidCallback: () {
Navigator.pop(context);
},
),
],
);
});
}

We will define _buildCupertinoActionSheetAction() function.

In this function, we will add IconData, title, and voidCallback. We will return a CupertinoActionSheetAction(). In this sheet, we will add a Row widget. In this widget, we will add an icon, title, and onPressed.

_buildCupertinoActionSheetAction({
IconData? icon,
required String title,
required VoidCallback voidCallback,
Color? color,
}) {
return CupertinoActionSheetAction(
child: Row(
children: [
if (icon != null)
Icon(
icon,
color: color ?? const Color(0xFF2564AF),
),
Expanded(
child: Text(
title,
textAlign: TextAlign.center,
style: AppTextStyles.regular(
fontSize: 17,
color: color ?? const Color(0xFF2564AF),
),
),
),
if (icon != null)
const SizedBox(
width: 25,
),
],
),
onPressed: voidCallback,
);
}

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

Output

Now, we will describe _getImageFrom({required ImageSource source}) function:

This is the main function, when the user clicks on the popup button and then pressed the camera /gallery button, then first shows pic the original size of the image and then shows after compressed image size.

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

Output

When we run the application, we ought to get the console output like the underneath.

I/flutter ( 8840): Before Compress 4750.7578125 kb
I/flutter ( 8840): After Compress 1095.669921875 kb

Now, after compressing the image, then the image will be moved to the crop part. The user will crop the image and the set to the fileImage is equal to the _croppedImage. The user will crop on any ratio and also, rotate the image.

_getImageFrom({required ImageSource source}) async {
final _pickedImage = await _picker.pickImage(source: source);
if (_pickedImage != null) {
var image = File(_pickedImage.path.toString());
final _sizeInKbBefore = image.lengthSync() / 1024;
print('Before Compress $_sizeInKbBefore kb');
var _compressedImage = await AppHelper.compress(image: image);
final _sizeInKbAfter = _compressedImage.lengthSync() / 1024;
print('After Compress $_sizeInKbAfter kb');
var _croppedImage = await AppHelper.cropImage(_compressedImage);
if (_croppedImage == null) {
return;
}
setState(() {
fileImage = _croppedImage;
});
}
}

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

Output

Code File:

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress_crop/app_helper.dart';
import 'package:flutter_image_compress_crop/app_text_style.dart';
import 'package:image_picker/image_picker.dart';

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

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

class _HomePageState extends State<HomePage> {
final _picker = ImagePicker();
File? fileImage;

_getImageFrom({required ImageSource source}) async {
final _pickedImage = await _picker.pickImage(source: source);
if (_pickedImage != null) {
var image = File(_pickedImage.path.toString());
final _sizeInKbBefore = image.lengthSync() / 1024;
print('Before Compress $_sizeInKbBefore kb');
var _compressedImage = await AppHelper.compress(image: image);
final _sizeInKbAfter = _compressedImage.lengthSync() / 1024;
print('After Compress $_sizeInKbAfter kb');
var _croppedImage = await AppHelper.cropImage(_compressedImage);
if (_croppedImage == null) {
return;
}
setState(() {
fileImage = _croppedImage;
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Image Crop & Compress Demo "),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.teal,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
if (fileImage != null)
Container(
height: 350,
width: 300,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(color: Colors.black12, width: 1),
borderRadius: const BorderRadius.all(Radius.circular(10)),
color: Colors.grey,
image: DecorationImage(
image: FileImage(fileImage!),
fit: BoxFit.cover,
)),
)
else
Container(
height: 350,
width: 350,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(color: Colors.black12, width: 1),
borderRadius: const BorderRadius.all(Radius.circular(10)),
color: Colors.grey[300],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/logo.png",
width: 150,
),
const SizedBox(
height: 20,
),
const Text(
"Image will be shown here",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 20),
),
],
),
),
const SizedBox(
height: 50,
),
Center(
child: ElevatedButton(
onPressed: () {
_openChangeImageBottomSheet();
},
child: const Text('Upload Image')),
),
],
),
);
}

_openChangeImageBottomSheet() {
return showCupertinoModalPopup(
context: context,
barrierDismissible: false,
builder: (context) {
return CupertinoActionSheet(
title: Text(
'Change Image',
textAlign: TextAlign.center,
style: AppTextStyles.regular(fontSize: 19),
),
actions: <Widget>[
_buildCupertinoActionSheetAction(
icon: Icons.camera_alt,
title: 'Take Photo',
voidCallback: () {
Navigator.pop(context);
_getImageFrom(source: ImageSource.camera);
},
),
_buildCupertinoActionSheetAction(
icon: Icons.image,
title: 'Gallery',
voidCallback: () {
Navigator.pop(context);
_getImageFrom(source: ImageSource.gallery);
},
),
_buildCupertinoActionSheetAction(
title: 'Cancel',
color: Colors.red,
voidCallback: () {
Navigator.pop(context);
},
),
],
);
});
}

_buildCupertinoActionSheetAction({
IconData? icon,
required String title,
required VoidCallback voidCallback,
Color? color,
}) {
return CupertinoActionSheetAction(
child: Row(
children: [
if (icon != null)
Icon(
icon,
color: color ?? const Color(0xFF2564AF),
),
Expanded(
child: Text(
title,
textAlign: TextAlign.center,
style: AppTextStyles.regular(
fontSize: 17,
color: color ?? const Color(0xFF2564AF),
),
),
),
if (icon != null)
const SizedBox(
width: 25,
),
],
),
onPressed: voidCallback,
);
}
}

Conclusion:

In the article, I have explained the basic structure of image compress & crop in a flutter; you can modify this code according to your choice. This was a small introduction to Image Compress & Crop 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 Image Compress & Crop in your flutter projects. We will show you what an Introduction is?. Show the implementations, and how to use Image Compress & Crop from the camera and gallery. Make a demo program for working 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.


GitHub Link:

find the source code of the Flutter Image Compress Crop Demo:

GitHub – flutter-devs/flutter_image_compress_crop_demo
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…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.


GetX State Management In Flutter

0

Flutter is without a doubt the best framework for developing cross-platform applications. Application improvement with Flutter is genuinely magnificent and simple since it gives a rich arrangement of adaptable widgets. Notwithstanding, some state the management choices will not permit you to feel the genuine force of the Flutter framework since you need to burn through your development time implementing a superfluous boilerplate.

State management is an intricate topic of conversation in Flutter. Be that as it may, many state management libraries, like Provider, are accessible, which most developers suggest. At the point when we begin building any application in a flutter, we should conclude which state management we want to utilize. It would be simpler for you to pursue this choice with this blog.

In this article, we will explore the GetX State Management In Flutter. We will see how to implement a demo program. I would like to explain GetX, a powerful flutter framework, and learn how to use the get package in your flutter applications.

get | Flutter Package
GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, and intelligent…pub.dev

Table Of Contents::

What is GetX?

Principles

Three Pillars Of GetX

Why GetX?

Implementation

Code Implement

Code File

Conclusion



What is GetX?:

GetX is a quick, stable, and light state management library in a flutter. There are so many State Management libraries in flutter like MobX, BLoC, Redux, Provider, and so forth.

GetX is additionally a strong miniature framework and utilizing this, we can oversee states, make routing, and can perform dependency injection.
State management permits you information transfer inside the application. What’s more, at whatever point information is passed, the application’s state is updated, thusly rebuilding the system.

Along these lines, developers must be especially cautious about managing the state of an application since state updation may at times appear to be exorbitant for a complex application.

Demo Module ::

Demo

This demo video shows how to implement a GetX State Management in a flutter and shows how GetX State Management will work using the get package in your flutter applications. We will show a routing example using GetX. It will be shown on your device.

Principles:

There are three principles of GetX:

  • > Performance: When contrasted with other state management libraries, GetX is best since it consumes the least assets and gives better execution. It doesn’t utilize ChangeNotifier or Streams. Take a gander at the beneath RAM graph portraying different state managers.
  • > Productivity: GetX’s syntax is simple so it is useful. It saves a ton of time for the developers and speeds up the application since it doesn’t utilize additional assets. It utilizes just those assets which are right now required and after its work is done, the assets will be free naturally. If every one of the assets is stacked into the memory, it won’t be simply useful. So better to involve GetX in this.
  • > Organization: GetX code is coordinated as View, Logic, route, and dependency injection. So we needn’t bother with any additional context to navigate different screens. We can navigate to the screen without utilizing the unique circumstance so we are not dependent on the widget tree.

Three Pillars Of GetX:

  • > State Management: There are two types of state management:-

Simple State Manager: It uses the GetBuilder function.

Reactive State Manager: It uses GetX and Obx.

  • > Route Management: To make Widgets like Snackbar, Bottomsheets, dialogs, and so forth. Then, at that point, we can involve GetX in it because GetX can assemble these widgets without utilizing context.
  • > Dependency Management: GetX has a straightforward yet strong answer for dependency management utilizing controllers. To bring data from different Classes then with the assistance of GetX, we can do this in a solitary line of code. Eg: Get.put()

Why GetX?:

GetX is a very lightweight and powerful state management solution for flutter.

  • > High performance: GetX utilizes as less assets as could be expected. It doesn’t rely upon Streams or ChangeNotifier. All things being equal, it utilizes low inertness GetValue and GetStream to further develop execution.
  • > Less code: You might be tired of implementing boilerplate in the bloc pattern and wasting development energy on superfluous codes. Time is money, isn’t that so? In GetX, you won’t compose any boilerplate. You can accomplish the same thing a lot quicker, with less code in GetX. Don’t bother making classes for the state and event, since these boilerplates don’t exist in GetX.
  • > No code generation: There is a compelling reason need to utilize code generators by any means. So your significant development time won’t squander more on running code generators(build_runner) whenever you change your code.
  • > Don’t worry about context: Your application context is important. Yet, sending the context from your view to the controller can be, here and there lumbering. In GetX, you don’t have to do this. You can get to controllers inside one more controller with no unique context.
  • > No unnecessary rebuilds: Undesirable modifies are an issue of state managers based on ChangeNotifier. Whenever you roll out an improvement in your ChangeNotifier class, all widgets that rely upon that ChangeNotifier class are rebuilt. Some rebuilds might be superfluous and expensive. It might diminish the application’s performance too. You don’t need to stress over this in GetX since it doesn’t utilize the ChangeNotifier by any means.
  • > Code organization is simple: Bloc’s popularity comes from its prevalent code sorting-out capacities. It makes it more straightforward to isolate your business rationale from the show layer. GetX is a characteristic development for this as true documentation says. In GetX, you can isolate the business rationale as well as the show layer.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
get: ^4.6.1

Step 2: Import

import 'package:get/get.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the main. dart file, we will return GetMaterialApp(). Also, we will add a theme for color, and a home for showing starting screen.

import 'package:flutter/material.dart';
import 'package:flutter_getx_statemanagement/splash_screen.dart';
import 'package:get/get.dart';

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

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

@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter GetX State Management Demo',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

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

We will create a class called MyHomePageController inside it and extend the GetxController class. We will add the final count is equal to 0. obs. In GetX, to make a variable observable — this means that when it changes, other parts of our application depending on it will be notified. To do this we simply need to add .obs to the variable initialization. So for our above count variable, we will add .obs to 0.

To wrap things up with the MyHomePageController we will implement the increment method.

import 'package:get/get.dart';

class HomePageController extends GetxController {
final count = 0.obs;
increment() => count.value++;
}

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

First, we will create inside the HomePage class, we will instantiate the HomePageController.

final HomePageController controller = Get.put(HomePageController());

For our count, we want the Text widget to be updated with the current count. So we will wrap the Text widget with Obx widget.

Obx(
() => Text(
'${controller.count.value}',
style: Theme.of(context).textTheme.headline4,
),
),

We will add floatingActionButton, we will call the increment method when the floatingActionButton is pressed.

floatingActionButton: FloatingActionButton(
onPressed: controller.increment,
tooltip: 'Increment',
backgroundColor: Colors.cyan,
child: const Icon(Icons.add),
),

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

Increment Output

> Snackbar:

On the home page, we will also create a show snackbar button using Getx in a flutter. In this button, onPressed method we will add inside Get. snackbar(). Also, we will add snackPosition and backgroundColor. In the child method, we will add the text ‘Show Snackbar’.

ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 18),
primary: Colors.teal,
),
onPressed: () {
Get.snackbar('GetX Snackbar', 'Yay! Awesome GetX Snackbar',
snackPosition: SnackPosition.BOTTOM,
backgroundColor: Colors.tealAccent);
},
child: const Text('Show Snackbar')),

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

Snackbar Output

> Dialog:

On the home page, we will also create a show alertDialog button using Getx in a flutter. In this button, onPressed method we will add inside Get. defaultDialog(). Also, we will add the title, middle text, textConfirm, confirmTextColor, and textCancel. In the child method, we will add the text ‘Show AlertDialog’.

ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 18),
primary: Colors.teal,
),
onPressed: () {
Get.defaultDialog(
title: 'GetX Alert',
middleText: 'Simple GetX alert',
textConfirm: 'Okay',
confirmTextColor: Colors.white,
textCancel: 'Cancel');
},
child: const Text('Show AlertDialog')),

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

Dialog Output

> Navigation In GetX:

On the home page, we will create a button ‘Go to next screen’ text and icon. On this button, onPressed method. We will add Get.to(() => const SecondPage()) for navigating screen without using context.

Padding(
padding: const EdgeInsets.all(12.0),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
minimumSize: const Size.fromHeight(40),
primary: Colors.teal,
),
child: Row(
children: const [
Spacer(),
Text("Go to next screen"),
SizedBox(
width: 20,
),
Expanded(
child: Icon(
Icons.arrow_right_alt,
size: 40,
))
],
),
onPressed: () {
Get.to(() => const SecondPage());
}),
),

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

Output

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

We will create a new SecondPage class. In this class, we will add a text and an ElevatedButton and wrap into it a Column widget.

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

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

@override
State<SecondPage> createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Second Page"),
centerTitle: true,
backgroundColor: Colors.teal,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Padding(
padding: EdgeInsets.all(12.0),
child: Text(
"The Flutter app developers at FlutterDevs have decades of industry experience under a single roof,"
" and this empowers us to serve you with excellence.",
style: TextStyle(fontSize: 17.0, fontWeight: FontWeight.w600),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.02,
),
Padding(
padding: const EdgeInsets.all(12.0),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
minimumSize: const Size.fromHeight(40),
primary: Colors.teal,
),
child: Row(
children: const [
Expanded(
flex: 1,
child: Icon(
Icons.arrow_back,
size: 30,
),
),
SizedBox(
width: 20,
),
Expanded(flex: 3, child: Text("Go to Home screen")),
],
),
onPressed: () {
Get.back();
}),
),
],
),
),
);
}
}

When the user presses the ‘Go to home screen’ button then, the user back to the home screen. On this onPressed method, we will add Get. back() for navigation without using context.

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

Second Page

When we run the application, we ought to get the console final output like the underneath.

Launching lib/main.dart on ONEPLUS A5010 in debug mode...
Running Gradle task 'assembleDebug'...
✓ Built build/app/outputs/flutter-apk/app-debug.apk.
Installing build/app/outputs/flutter-apk/app.apk...
Debug service listening on ws://127.0.0.1:38103/2vooOVfhIIY=/ws
Syncing files to device ONEPLUS A5010...
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
[GETX] GOING TO ROUTE /HomePage
[GETX] Instance "HomePageController" has been created
[GETX] Instance "HomePageController" has been initialized
[GETX] OPEN DIALOG 849896188
[GETX] CLOSE DIALOG 849896188
[GETX] GOING TO ROUTE /SecondPage
[GETX] CLOSE TO ROUTE /SecondPage
[GETX] GOING TO ROUTE /SecondPage
[GETX] CLOSE TO ROUTE /SecondPage

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_getx_statemanagement/view_screens/second_page.dart';
import 'package:get/get.dart';
import '../controllers/home_page_controller.dart';

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

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
final HomePageController controller = Get.put(HomePageController());

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter GetX State Management Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.teal,
),
floatingActionButton: FloatingActionButton(
onPressed: controller.increment,
tooltip: 'Increment',
backgroundColor: Colors.cyan,
child: const Icon(Icons.add),
),
body: Center(
child: Column(
children: [
const SizedBox(
height: 30,
),
Image.asset(
"assets/logo.png",
width: 300,
),
const SizedBox(
height: 50,
),
const Text(
'You have pushed the button this many times:',
),
Obx(
() => Text(
'${controller.count.value}',
style: Theme.of(context).textTheme.headline4,
),
),
const SizedBox(
height: 20,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 18),
primary: Colors.teal,
),
onPressed: () {
Get.snackbar('GetX Snackbar', 'Yay! Awesome GetX Snackbar',
snackPosition: SnackPosition.BOTTOM,
backgroundColor: Colors.tealAccent);
},
child: const Text('Show Snackbar')),
const SizedBox(
height: 10,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 18),
primary: Colors.teal,
),
onPressed: () {
Get.defaultDialog(
title: 'GetX Alert',
middleText: 'Simple GetX alert',
textConfirm: 'Okay',
confirmTextColor: Colors.white,
textCancel: 'Cancel');
},
child: const Text('Show AlertDialog')),
Padding(
padding: const EdgeInsets.all(12.0),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
minimumSize: const Size.fromHeight(40),
primary: Colors.teal,
),
child: Row(
children: const [
Spacer(),
Text("Go to next screen"),
SizedBox(
width: 20,
),
Expanded(
child: Icon(
Icons.arrow_right_alt,
size: 40,
))
],
),
onPressed: () {
Get.to(() => const SecondPage());
}),
),
],
),
),
);
}
}

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

Home Page

Conclusion:

In the article, I have explained the basic structure of GetX State Management in a flutter; you can modify this code according to your choice. This was a small introduction to GetX State Management 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 GetX State Management in your flutter projects. We will show you what GetX is?. Show the principles, and why GetX, etc of GetX State Management. Make a demo program for working with GetX. 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.


GitHub Link:

find the source code of the Flutter GetX State Management Demo:

GitHub – flutter-devs/flutter_getx_state_management_demo
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…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.


2026 Ultimate Guide to Dialog Implementation with GetX in Flut…

0

Dialogs are fundamental parts of mobile Apps. They help to pass cautions and significant messages as well as on to do specific activities. At the point when flutter developers make a dialog in Flutter, it utilizes context and builder to make a Dialog. However, this training isn’t appropriate for a developer to foster Dialogs utilizing contexts and builders.

In this article, we will explore the Dialog Using GetX in Flutter. We will also implement a demo program and learn how to create Dialog using the get package in your flutter applications.

get | Flutter Package
GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, intelligence…pub.dev

Table Of Contents::

Introduction

Constructor

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

At the point when we need to show anything like the form then we can make this Dialog involving the GetX library in Flutter. We can make Dialog utilizing GetX with basic code and extremely simple to make a dialog. It doesn’t utilize context and builder to make Dialog.

GetX is additional light and strong solution for Flutter. It joins elite performance state management, intelligent dependency injection, and route management rapidly and essentially.

Demo Module ::

This demo video shows how to create a dialog in a flutter and shows how dialog will work using the get package in your flutter applications, and also using different properties. It will be shown on your device.

Constructor:

To utilize Get.defaultDialog(), you need to call the constructor underneath:

Future<T?> defaultDialog<T>({
String title = "Alert",
EdgeInsetsGeometry? titlePadding,
TextStyle? titleStyle,
Widget? content,
EdgeInsetsGeometry? contentPadding,
VoidCallback? onConfirm,
VoidCallback? onCancel,
VoidCallback? onCustom,
Color? cancelTextColor,
Color? confirmTextColor,
String? textConfirm,
String? textCancel,
String? textCustom,
Widget? confirm,
Widget? cancel,
Widget? custom,
Color? backgroundColor,
bool barrierDismissible = true,
Color? buttonColor,
String middleText = "Dialog made in 3 lines of code",
TextStyle? middleTextStyle,
double radius = 20.0,
List<Widget>? actions,
WillPopCallback? onWillPop,
GlobalKey<NavigatorState>? navigatorKey,
})

Properties:

There are some properties of Get.defaultDialog() are:

  • > title: In this property is used to the title of the Dialog. By default, the title is “Alert”.
  • > titleStyle: In this property is used to the style given to the title text using TextStyle.
  • > content: In this property is used to the content given to the Dialog and should use Widget to give content.
  • > middleText: In this property is used in the middle text given to the Dialog. If we utilize content also then content widget data will be sown.
  • > barrierDismissible: In this property is used if we want to close the Dialog by clicking outside the dialog then its value should be true else false. By default, its value is true.
  • > middleTextStyle: In this property is used to the style given to the middle text using TextStyle.
  • > radius: In this property is utilized to the radius of the Dialog provided. By default, its value is 20.
  • > backgroundColor: In this property is used as the background color of the Dialog.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
get: ^4.6.1

Step 2: Import

import 'package:get/get.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

We have utilized GetMaterialApp rather than MaterialApp because we are building our application utilizing the GetX library. If we don’t utilize GetMaterialApp then, at that point, its functionalities won’t work.

return GetMaterialApp(
title: 'Dialog Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Splash(),
debugShowCheckedModeBanner: false,
);

We will create a Home class in the main.dart file

In the body, we will add a Center widget. In this widget, we will add a Column widget that was mainAxisAlignment was center. We will add things, first, we will add an image, and second, we will add an ElevatedButton with child and style properties. In the onPressed function, we will add Get.defaultDialog(). We will deeply describe it below.

Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset("assets/logo.png", scale: 14,),
SizedBox(height: 80,),
ElevatedButton(
child: Text('Show Dialog'),
style: ElevatedButton.styleFrom(
primary: Colors.teal,
onPrimary: Colors.white,
shadowColor: Colors.tealAccent,
textStyle: TextStyle(
fontSize: 18,
),
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
minimumSize: Size(120, 50),
),
onPressed: () {
Get.defaultDialog();

},
),
],
)),

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

Home Screen

Now, we will deeply describe Get.defaultDialog():

Now you saw how easy it is to get a dialog with very few lines using GetX in Flutter. You can also customize it with different options given by GetX. We will add title, middle text, backgroundColor, titleStyle, middleTextStyle and radius.

Get.defaultDialog(
title: "Welcome to Flutter Dev'S",
middleText: "FlutterDevs is a protruding flutter app development company with "
"an extensive in-house team of 30+ seasoned professionals who know "
"exactly what you need to strengthen your business across various dimensions",
backgroundColor: Colors.teal,
titleStyle: TextStyle(color: Colors.white),
middleTextStyle: TextStyle(color: Colors.white),
radius: 30
);

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_dialog_getx_demo/splash_screen.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Dialog Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Splash(),
debugShowCheckedModeBanner: false,
);
}
}

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Dialog Using GetX In Flutter'),
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset("assets/logo.png", scale: 14,),
SizedBox(height: 80,),
ElevatedButton(
child: Text('Show Dialog'),
style: ElevatedButton.styleFrom(
primary: Colors.teal,
onPrimary: Colors.white,
shadowColor: Colors.tealAccent,
textStyle: TextStyle(
fontSize: 18,
),
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
minimumSize: Size(120, 50),
),
onPressed: () {
Get.defaultDialog(
title: "Welcome to Flutter Dev'S",
middleText: "FlutterDevs is a protruding flutter app development company with "
"an extensive in-house team of 30+ seasoned professionals who know "
"exactly what you need to strengthen your business across various dimensions",
backgroundColor: Colors.teal,
titleStyle: TextStyle(color: Colors.white),
middleTextStyle: TextStyle(color: Colors.white),
radius: 30
);
},
),
],
)),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Dialog Using GetX in a flutter; you can modify this code according to your choice. This was a small introduction to Dialog Using GetX 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 Dialog Using GetX in your flutter projects. We will show you what the Introduction is?. Make a demo program for working Dialog Using GetX plugins. In this blog, we have examined the Dialog Using GetX of the flutter app. I hope this blog will help you in the comprehension of the Dialog in a better way. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: Pagination using GetX in Flutter

Related: Rest API Using GetX

Related: GetX State Management In Flutter


Frequently Asked Questions

How can I create a dialog box in Flutter using the GetX state management library?

You can create a dialog box in Flutter by using Get.dialog() function from the GetX package.

What are the benefits of using GetX for creating dialogs in Flutter instead of other state management solutions?

GetX simplifies the creation and handling of dialogs, making it easier to manage complex UI states.

Can I customize the appearance of dialogs created using GetX in Flutter?

Yes, you can customize the appearance of your dialogs by passing a custom widget to the Get.dialog() function.

ExpansionPanelList In Flutter

0

In this article, we will explore the ExpansionPanelList In Flutter. We will implement an expansion panel list demo program and learn how to customize its style with different properties in your flutter applications.

Table Of Contents::

Expansion Panel List

Constructor

Properties

Code Implement

Code File

Conclusion



Expansion Panel List:

It is a material widget in flutter which is like listView. It can just have Expansion panels as children. In certain cases, we may need to show a list where the children can expand/collapse to show/hide some detailed data. To show such a list flutter gives a widget called ExapansionPanelList.

In this list, every child is an ExpansionPanel widget. We can’t utilize different widgets as children for this list. We can deal with the adjustment of state( Expansion or collapse ) of a thing with the assistance of ExpansionCallback property.

Demo Module :

This demo video shows how to create an expansion panel List in a flutter. It shows how the expansion panel List will work in your flutter applications. It shows a list where the children can expand/collapse to show/hide some detailed information. It will be shown on your device.

Constructor:

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

const ExpansionPanelList({
Key? key,
this.children = const <ExpansionPanel>[],
this.expansionCallback,
this.animationDuration = kThemeAnimationDuration,
this.expandedHeaderPadding = _kPanelHeaderExpandedDefaultPadding,
this.dividerColor,
this.elevation = 2,
})

Properties:

There are some properties of ExpansionPanelList are:

  • > children: This property is used by the children of the expansion panel List. They are laid out similarly to [ListBody].
  • > expansionCallback: This property is used to the callback that gets called whenever one of the expand/collapse buttons is pressed. The arguments passed to the callback are the index of the pressed panel and whether the panel is currently expanded or not.
  • > animationDuration: This property is used while expanding or collapsing we can observe some animation take place for a certain period. We can change that duration by using the animationDuration property of the expansion panel List. We just have to provide Duration in either microseconds, milliseconds, or minutes as value.
  • > expandedHeaderPadding: This property is used to the padding that surrounds the panel header when expanded. By default, 16px of space is added to the header vertically (above and below) during expansion.
  • > dividerColor: This property is used to define the color for the divider when [ExpansionPanel.isExpanded] is false. If `dividerColor` is null, then [DividerThemeData.color] is used. If that is null, then [ThemeData.dividerColor] is used.
  • > elevation: This property is used to define elevation for the [ExpansionPanel] while it’s expanded. This uses [kElevationToShadow] to simulate shadows, it does not use [Material]’s arbitrary elevation featureBy default, the value of elevation is 2.

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we will generate dummy data. We will create a list <Map<String, dynamic>> and add variable _items equal to generating a list. In this list, we will add number, id, title, description, and isExpanded.

List<Map<String, dynamic>> _items = List.generate(
10,
(index) => {
'id': index,
'title': 'Item $index',
'description':
'This is the description of the item $index. Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
'isExpanded': false
});

In the body, we will add ExpansionPanelList() widget. In this widget, we will add elevation was three, expansionCallback was added index and isExpanded in the bracket. We will add setState() method. Inside the method, we will add _items[index][‘isExpanded’] equal not isExpanded.

ExpansionPanelList(
elevation: 3,
expansionCallback: (index, isExpanded) {
setState(() {
_items[index]['isExpanded'] = !isExpanded;
});
},
animationDuration: Duration(milliseconds: 600),
children: _items
.map(
(item) => ExpansionPanel(
canTapOnHeader: true,
backgroundColor:
item['isExpanded'] == true ? Colors.cyan[100] : Colors.white,
headerBuilder: (_, isExpanded) => Container(
padding:
EdgeInsets.symmetric(vertical: 15, horizontal: 30),
child: Text(
item['title'],
style: TextStyle(fontSize: 20),
)),
body: Container(
padding: EdgeInsets.symmetric(vertical: 15, horizontal: 30),
child: Text(item['description']),
),
isExpanded: item['isExpanded'],
),
)
.toList(),
),

We will add animationDuration was 600 milliseconds. We will add children as variable _items were mapped to the ExpansionPanel() widget. In this widget, we will add canTapOnHeader was true, backgroundColorheaderBuilder return the Container() widget. In this widget, we will add padding and on its child property, we will add text. In the body, we will add Conatiner and its child property, we will add text. 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_expansion_panel_list/splash_screen.dart';

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

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

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

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

class _HomePageState extends State<HomePage> {
List<Map<String, dynamic>> _items = List.generate(
10,
(index) => {
'id': index,
'title': 'Item $index',
'description':
'This is the description of the item $index. Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
'isExpanded': false
});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Flutter Expansion Panel List Demo'),
),
body: SingleChildScrollView(
child: ExpansionPanelList(
elevation: 3,
// Controlling the expansion behavior
expansionCallback: (index, isExpanded) {
setState(() {
_items[index]['isExpanded'] = !isExpanded;
});
},
animationDuration: Duration(milliseconds: 600),
children: _items
.map(
(item) => ExpansionPanel(
canTapOnHeader: true,
backgroundColor:
item['isExpanded'] == true ? Colors.cyan[100] : Colors.white,
headerBuilder: (_, isExpanded) => Container(
padding:
EdgeInsets.symmetric(vertical: 15, horizontal: 30),
child: Text(
item['title'],
style: TextStyle(fontSize: 20),
)),
body: Container(
padding: EdgeInsets.symmetric(vertical: 15, horizontal: 30),
child: Text(item['description']),
),
isExpanded: item['isExpanded'],
),
)
.toList(),
),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the ExpansionPanelList in a flutter; you can modify this code according to your choice. This was a small introduction to ExpansionPanelList 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 ExpansionPanelList in your flutter projects. We will show you what the ExpansionPanelList is?. Show constructor and properties of the ExpansionPanelListr. Make a demo program for working ExpansionPanelList, and it shows a list where the children can expand/collapse to show/hide some detailed information in your flutter application. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter