Google search engine
Home Blog Page 50

Flutter Migrate to Navigator 2.0

0

Flutter team come up with a new update. A declarative API to set the history stack of the Navigator and a new Router widget to configure the Navigator based on events.

Now Navigator that allows setting the navigator’s history stack in a declarative way by providing a list of immutable Pages

For those who don’t know the difference between declarative and imperative programming?


Brief introduction :

“Imperative programming is like how you do something, and declarative programming is more like what you do.”

Code example :

Imperative style :

// Imperative style
b.setColor(red)
b.clearChildren()
ViewC c3 = new ViewC(...)
b.add(c3)

Declarative style :

// Declarative style
return ViewB(
color: red,
child: ViewC(...),
)

For more info check out this link

Why we need Navigator 2.0?

  1. It is difficult to push or pop multiple pages or remove a page in Navigator 1.0.

2. Now APIs enable more fine-tuned control over the screens in your app.

Let’s see how to migrate to Navigator 2.0

First, wrap it with Navigator.

Navigator(
pages: [
// it takes a list of pages
],
onPopPage: (route, result) {
  },
),

And What exactly page is?

MaterialPage(
key: ValueKey('uniqueKey'),
child: Screen2(),
),

What onPopPage callback do :

when pop is invoked but the current Route corresponds to a Page found in the pages list. And The result argument is the value with which the route is to complete. This callback is responsible for calling Route.didPop() and returning whether this pop is successful.

The Navigator widget should be rebuilt with a pages list that does not contain the Page for the given Route. The next time the pages list is updated, if the Page corresponding to this Route is still present, it will be interpreted as a new route to display.

Navigator(
pages: [
MaterialPage(
key: ValueKey('uniqueKey'),
child: Screen2(),
),
],
onPopPage: (route, result) {
if (route.didPop(result)) return true;

return false;
},
)

Let’s dig into code:

Here you can see on tapping the text callback update our bool value. By default, it lands to Screen1 and on updating bool value it moves to Screen2.

class _MyAppState extends State<MyApp> {
bool isStacked = false;

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Navigator(
pages: [
MaterialPage(
key: ValueKey('unique '),
child: Screen1(
onTap: (value) {
isStacked = value;
setState(() {});
},
),
),
if (isStacked == true)
MaterialPage(
child: Screen2(),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) return false;
setState(() => isStacked = false);
return true;
},
),
);
}
}

Screen1 view:

class Screen1 extends StatelessWidget {
Function(bool) onTap;

Screen1({this.onTap});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Navigator 2.0"),
),
body: Center(
child: InkWell(
onTap: () {
onTap(true);
},
child: Text(
'Screen 1 \n tap on text to maove to screen2',
),
),
),
);
}
}

Screen 2 :

class Screen2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: ()
{
Navigator.of(context).pop();
},
icon: Icon(
Icons.arrow_back_ios ,
),
),
title: Text("Back to Screen 1"),
),
body: Center(
child: InkWell(
child: Text(
'Screen 2 ',
),
),
),
);
}
}

Check out the full code :

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

A warm welcome for all the queries and suggestion. If you find anything that could be improved please let me know, I would love to improve


From Our Parent Company Aeologic

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

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

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

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

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

Creating Stateful Dialog Form In Flutter

0

In this blog, I will talk about how to create a stateful dialog form using the stateful builder. Where you can take TextField checkbox or any other type input on dialog. which you may need. We will create our own state of a dialog using the stateful builder and we will use a form widget with a global key which flutters to validate textfield. Let us now implement stateful dialog in your flutter application. Now let’s start.


Table of Contents :

Flutter

Stateful Dialog Form

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time 

Stateful Dialog Form:

A StatefulBuilder is such a builder. In which there is a mutable. Which can have a change of state. what makes it special is that it has to rebuild its special widget which comes under the Statefulbuilder. Stateful builder widget that we use can be used to update a specific element in the UI if the stateless widget. and moving the stateless widget to the stateless widget and getting rid of the stateful builder can store the same result. and the whole widget is not rebuilt again and again.

Demo Module :

Code Implement :

Create a new dart file calledflutter_sateful_dialog inside the lib folder.

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

Using the Global key we use the global key to access and manipulate the status of our form and external Scaffold widget. The Global case allows us to access unique identities that our widget in the flutter widget tree is assigned. As we create a form application using it. In this, we have a separate input box. we stop the rudimentary validation check on it and when it satisfies those validation conditions and the user interface changes to show that.

represent

Have a Look at the code Implementation :

return await showDialog(
context: context,
builder: (context) {
bool isChecked = false;
return StatefulBuilder(builder: (context, setState) {
return AlertDialog(
content: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: _textEditingController,
validator: (value) {
return value.isNotEmpty ? null : "Enter any text";
},
decoration:
InputDecoration(hintText: "Please Enter Text"),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("Choice Box"),
Checkbox(
value: isChecked,
onChanged: (checked) {
setState(() {
isChecked = checked;
});
})
],
)
],
)),
title: Text('Stateful Dialog'),
actions: <Widget>[
InkWell(
child: Text('OK '),
onTap: () {
if (_formKey.currentState.validate()) {
// Do something like updating SharedPreferences or User Settings etc.
Navigator.of(context).pop();
}
},
),
],
);
});
});

We have used the alert dialog in this screen, inside which we have used the SatefulBuilder. A Statefulbuilder widget that has the power to the state setter function it is. used to build itself rather than the typical state of the entire widget to pass to the builder. And in this, we have taken the input box of type TextFormfield and used the checkbox.TextFormField has a function of the type validator that we have used for applying in the input box.

Code File:

import 'package:flutter/material.dart';

class StatefulDialog extends StatefulWidget {
@override
_StatefulDialogState createState() => _StatefulDialogState();
}

class _StatefulDialogState extends State<StatefulDialog> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

final TextEditingController _textEditingController = TextEditingController();


Future<void> showInformationDialog(BuildContext context) async {
return await showDialog(
context: context,
builder: (context) {
bool isChecked = false;
return StatefulBuilder(builder: (context, setState) {
return AlertDialog(
content: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: _textEditingController,
validator: (value) {
return value.isNotEmpty ? null : "Enter any text";
},
decoration:
InputDecoration(hintText: "Please Enter Text"),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("Choice Box"),
Checkbox(
value: isChecked,
onChanged: (checked) {
setState(() {
isChecked = checked;
});
})
],
)
],
)),
title: Text('Stateful Dialog'),
actions: <Widget>[
InkWell(
child: Text('OK '),
onTap: () {
if (_formKey.currentState.validate()) {
// Do something like updating SharedPreferences or User Settings etc.
Navigator.of(context).pop();
}
},
),
],
);
});
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Center(
child: FlatButton(
color: Colors.deepOrange,
onPressed: () async {
await showInformationDialog(context);
},
child: Text(
"Stateful Dialog",
style: TextStyle(color: Colors.white, fontSize: 16),
)),
),
),
);
}
}

Conclusion :

In this article, I have explained a Creating Stateful Dialog Form demo, you can modify and experiment according to your own, this little introduction was from the Creating Stateful Dialog Form from our side.

I hope this blog helps will provide you with sufficient information in Trying up the Creating Stateful Dialog Form in your flutter project. So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

The New Material Buttons at Version 1.22 in Flutter

0

In this blog, I will talk about The New material Button Version 1.22 in a flutter. We will implement a demo of the New material Button in a flutter in your flutter applications. Now let’s start.


Table of Contents :

Flutter

New Material Buttons Version 1.22

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single code base in record time ”

New Material Buttons Version 1.22 :

Flutter New material button has come with flutter new version 1.22. While the old buttons still there. It basically involved creating and using custom buttons. While this is not the case with 1.22. Now you can easily set that theme in it. This will apply to all buttons of the type chosen globally.

As you can see a table below. That the buttons and their themes replace the existing ones:

Demo Module :

Code Implement :

  1. TextButton: The TextButton is a replacement for FlatButton.We are commonly used for dialogs and low pronunciation functions, including those in cards. It does not have visible limitations. This is also the case with the button theme data is sent to the theme we pass these to the property. This is the new property in them data. And one of them is the TextButtonTheme related subject property. This TextButton accepts the theme data. within which we can set the color of the button, etc.
TextButton(
onPressed: () {
print('Pressed TextButton');
_showMessageInScaffold("Text Button!");
},
child: Text('Text Button'),
),

The style of a TextButton can be override with its style parameter. The style of all text buttons in an app can be override with the theme data TextButton end. And to override the background color of the button create a Button Style with the help of TextButtonTheme.The selected button state measure the background color.

textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
primary: Colors.orange,
),
),

2.ElevatedButton: Elevated Button is a replacement for RaisedButton which is used as the primary actions in the app. And also we can change the size color of the button globally with the help of ElevatedButtonThemeData: .

ElevatedButton(
onPressed: () {
print('Pressed ElevatedButton');
_showMessageInScaffold("Elevated Button! ");
},
child: Text('Elevated Button'),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
onPrimary: Colors.white,
primary: Colors.blue,
),
),

3. OutlinedButton: The OutlinedButton is a replacement for OutlineButton. And this is a medium thrust button. They have actions that are important. But they do not perform primarily in any app.

OutlinedButton(
onPressed: () {
_showMessageInScaffold("Outlined Button!");
},
child: Text('Outlined Button'),
),

The style of an OutlinedButton can be override with its style parameter. The style of all text buttons in an app can be override with the theme data OutlinedButton end. And to be override the background color of the button create a Button Style with the help of OutlinedButtonThemeData.The selected button state measure the background color .

outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
primary: Colors.red,
),
),

Code File :

import 'package:flutter/material.dart';

class FlutterNewMaterialButton extends StatefulWidget {
@override
_FlutterNewMaterialButtonState createState() =>
_FlutterNewMaterialButtonState();
}

class _FlutterNewMaterialButtonState extends State<FlutterNewMaterialButton> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

double _height;
double _width;

void _showMessageInScaffold(String message) {
try {
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text(message),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
print('Action in Snackbar has been pressed.');
},
),
));
} on Exception catch (e, s) {
print(s);
}
}

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.blue[300],
title: Text('New Material Buttons'),
),
body: SafeArea(
child: Container(
height: _height,
width: _width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
print('Pressed ElevatedButton');
_showMessageInScaffold("Elevated Button! ");
},
child: Text('Elevated Button'),
),
TextButton(
onPressed: () {
print('Pressed TextButton');
_showMessageInScaffold("Text Button!");
},
child: Text('Text Button'),
),
OutlinedButton(
onPressed: () {
_showMessageInScaffold("Outlined Button!");
},
child: Text('Outlined Button'),
),
],
),
),
),
);
}
}

return MaterialApp(
debugShowCheckedModeBanner: false,
// theme: ThemeData(),
initialRoute: '/',
onGenerateRoute: Routes.onGenerateRoute,
theme: ThemeData.from(
colorScheme: ColorScheme.light(),
).copyWith(
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
primary: Colors.orange,
),
),

elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
onPrimary: Colors.white,
primary: Colors.blue,
),
),

outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
primary: Colors.red,
),
),
),
);

Conclusion :

In this article, I have explained a New Material Buttons Version 1.22 demo, you can modify and experiment according to your own, this little introduction was from the New Material Buttons Version 1.22 from our side.

I hope this blog helps will provide you with sufficient information in Trying up the New Material Buttons Version 1.22 in your flutter project. So please try it.

❤ ❤ Thanks for reading this article ❤❤


From Our Parent Company Aeologic

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

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

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

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

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

Spacer Class In Flutter

0

Introduction :

Spacer widget is used to create a customized spacing between the widget. It is mainly used to create an adjustable spacing between the widgets in a flex container like Rows and Columns.


Table of contents:

:: Introduction to Spacer class

:: Properties used in Spacer


Spacer class :

Flutter although provides spacing alignments that are already predefined such as spaceAround, spaceEvenlyand spaceBetween but still provides an additional Spacer widget just for adjustable spacing as per their need accordingly. The main advantage of using Spacer is that the spacing provided between the widgets is set according to our requirements.

Properties used in Spacer class :

key: Controls how one widget replaces another widget in the tree.

flex: This property is used to define how much space is required to take up between the widgets. This property creates a space between widgets in form of ratio division. It takes an integer value and its default value is 1.

Sample :

This is how the spacing between the container looks like :

As you can see above the space between the container is equally divided in an equal ratio accordingly.

Now let’s try to understand this widget by taking more examples:

Let’s Start:

Here above the code, we have used flex property with its different-different values inside the Spacer widget. Spacer widget uses flex value 3 between the first two containers and flex value 2 between the second and third container, and value 1 between the third and fourth container while no Spacer widget is used after the fourth container.

This is how it looks ::

In the above example, the flex property is used inside the Spacer widget. The flex value in total is 3 + 2 + 1 = 6 .

Now let’s understand the spacing ratio. The space between the first and second container will be 3/6 of the applied space while the space between the second and the third container will be 2/6 of the space while the flex value between the third and fourth container is 1 so it will be having 1/6 of an applied spacing.

Remember the default value of flex is 1. If the flex property is not used inside the Spacer widget it will automatically set it as its default value.

Note:: The same concept can also be applied to Column as already mentioned above.


For more info visit down the link:

Spacer class
API docs for the Spacer class from the widgets library, for the Dart programming language.api.flutter.dev


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think are required…✔

From Our Parent Company Aeologic

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

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

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

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

Wrap Class In Flutter

0

Introduction :

Wrap class is a widget that is used to display its children or widget in a multiple horizontal or vertical direction. Wrap class is basically used to wrap our children in a direction as provided which looks similar to somewhat Rows and Columns.


Table of content :

:: Introduction to Wrap class

:: Properties used in a Wrap class


Wrap class :

Wrap class is used to align or adjust multiple widgets vertically or horizontally similar to Rows and Columns. It can be adjusted either in form of Row or Column as required. Wrap class automatically align or fit the widgets accordingly in its cross-axis area without displaying an Overflow message similar to Rows and Columns.

Properties :

alignment: this property is used to describe how the children should align in the main axis. Its default value is WrapAlignment.start.

clipBehavior: This property takes in Clip enum as the object and decides whether the content should be clipped or not according to the option.

crossAxisAlignment: this property is used to describe how the children should be aligned relative to each other in the cross-section part. Its default value is WrapCrossAlignment.start .

direction: This property uses a direction as the main axis. By default axis is horizontal and we can change it to vertical by using Axis.verical its value.

runAlignment: this property describes how the run should be placed in the cross axis. Its default value is WrapAlignment.start.

spacing: this property is used to place a space between children in the main axis.

runSpacing: this property is used to place a space between the children along a cross axis.

textDirection: this property is used to arrange the children inside Wrap class in the given direction.

verticalDirection: this property is used to determine the order to lay children out vertically and how to interpret start and end in the vertical direction.

Sample :

This is how this sample looks :

But if we have used Row instead of this Wrap class then the widget may have Overflowed by pixels as shown below…👀

To fix such issues we uses Wrap class instead of using Rows and Columns.

Implementation:

As shown above we can also apply other properties also…👍


For more info visit down the link:

Wrap class
A widget that displays its children in multiple horizontal or vertical runs. A Wrap lays out each child and attempts to…api.flutter.dev


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think are required…✔

From Our Parent Company Aeologic

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

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

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

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

Dropdown In Flutter

0

In this article, We will explain about The dropdown button in a flutter. A dropdown button is a material design button. So let’s apply a demo of the dropdown button in your flutter applications.


Table of Contents :

Flutter

Dropdown Button

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single code base in record time ”

Dropdown Button:

We use the Dropdown Button to display any Dropdown List item as we can change its style according to it. Such as its background color, border secular etc. As this Dropdown list because it is a clickable widget. Which shows the list item we have selected. The Dropdown Button has DropDownMenuItem. We initialize whatever is to be shown in the list. and the Dropdown button has a function named onChnaged. When a user clicks on an item from the dropdown. So it triggers and executes the triggered function.

Demo Module :

Code Implement :

Create a new dart file calledflutter_dropdown_button_demo inside the lib folder.

Have a Look at the code Implementation :

DropdownButton<String>(
focusColor:Colors.white,
value: _chosenValue,
//elevation: 5,
style: TextStyle(color: Colors.white),
iconEnabledColor:Colors.black,
items: <String>[
'Android',
'IOS',
'Flutter',
'Node',
'Java',
'Python',
'PHP',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value,style:TextStyle(color:Colors.black),),
);
}).toList(),
hint:Text(
"Please choose a langauage",
style: TextStyle(
color: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w500),
),
onChanged: (String value) {
setState(() {
_chosenValue = value;
});
},
),

We have explained the Dropdown in this screen. We list items using the Dropdown Button. To show on the click of a button, in the Dropdown Button we have initialized some list items. Which is of string type. That will show us the item.

Seeing the screen above. There is a list showing in this screen, which will initialize the value of the DropdownMenuItemin the Dropdown Button and will show the click value on the click of its item in onChanged.

Code File :

import 'package:flutter/material.dart';

class DropDownDemo extends StatefulWidget {
@override
_DropDownDemoState createState() => _DropDownDemoState();
}

class _DropDownDemoState extends State<DropDownDemo> {
String _chosenValue;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DropDown'),
),
body: Center(
child: Container(
padding: const EdgeInsets.all(0.0),
child: DropdownButton<String>(
value: _chosenValue,
//elevation: 5,
style: TextStyle(color: Colors.black),

items: <String>[
'Android',
'IOS',
'Flutter',
'Node',
'Java',
'Python',
'PHP',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
hint: Text(
"Please choose a langauage",
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w600),
),
onChanged: (String value) {
setState(() {
_chosenValue = value;
});
},
),
),
),
);
}
}

Conclusion :

In this article, I have explained a Dropdown Button demo, you can modify and experiment according to your own, this little introduction was from the Dropdown Button from our side.

I hope this blog helps will provide you with sufficient information in Trying up the Dropdown Button demo in your flutter project. So please try it.

❤ ❤ Thanks for reading this article ❤❤


From Our Parent Company Aeologic

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

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

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

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

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

Firebase Authentication using Provider in Flutter

0

Things that you may likely learn from the Blog :

  • How to implement authentication into your flutter app?
  • How to use the provider package for state management?
  • How to use git_it package to inject dependencies?
  • How to implement routes for navigation?

Introduction To Provider

Provider is not a state management, it is just a state management helper. Provider package provides us various widgets that help us to consume various changes in values and then rebuild the widget when any changes occur. The most frequently used classes of provider package are Consumer, ChangeNotifier, ChangeNotifierProvider. The model class that is made available to the app widget tree, extends the ChangeNotifier. This class contains all the app state managing methods and variables and objects. Whenever we update the state of the app we need to call notifiyListeners() to notify all the widgets who are listening to that particular change so that the UI can be rebuilt and updated. ChangeNotifierProvider is wrapped at the top of the app widget so that all the widget of the app widget tree can listen to the change made. There are two methods that can be used to consume the updated data. Using Provider.of() and Consumer widget.

Install the bellow packages inside your pubspec.yaml file

provider | Flutter Package
English | Português A wrapper around InheritedWidget to make them easier to use and more reusable. By using provider…pub.dev

get_it | Dart Package
This is a simple Service Locator for Dart and Flutter projects with some additional goodies highly inspired by Splat…pub.dev

firebase_auth | Flutter Package
A Flutter plugin to use the Firebase Authentication API. To learn more about Firebase Auth, please visit the Firebase…pub.dev

firebase_core | Flutter Package
A Flutter plugin to use the Firebase Core API, which enables connecting to multiple Firebase apps. To learn more about…pub.dev


Let’s learn how to use routes for navigation

MaterialApp provides us onGenerateRoute, initialRoute functionality to implement navigation using routes. onGenerateRoute takes RouteSetting as a parameter and returns a Route.

Let’s create a separate class to initialize all the navigation cases using the switch method. We will make a static Route<dynamic> type method that takes RouteSettings parameters.

routers.dart file

import 'package:flutter/material.dart';
import 'package:flutter_chat_app/ui/homePage.dart';
import 'package:flutter_chat_app/ui/landingPage.dart';

class Routers {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case 'home':
return MaterialPageRoute(builder: (_) => HomePage());
case 'landing':
return MaterialPageRoute(builder: (_) => LandingPage());
default:
return MaterialPageRoute(builder: (_) {
return Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}'),
),
);
});
}
}
}

Now we can provide the onGenerateRoute property also initialize the initalRoute .

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: 'landing',
onGenerateRoute: Routers.generateRoute,
);
}
}

For navigation, we can use pushNamed method to navigate to another screen using the name of the route name defined in the router.dart .

onPressed: () async {
Navigator.pushNamed(context, 'route_name');
}

Let’s code

To manage the state of the app we will use enums ViewState, AuthState .

enum ViewState { Ideal, Busy }
enum AuthState { SignIn, SignUp }

Let’s build a BaseModel class that extends ChangeNotifier . This class will contain all the methods that we will use the update the UI.

import 'package:flutter/material.dart';
import 'package:flutter_chat_app/enum/appState.dart';

class BaseModel extends ChangeNotifier {
ViewState _viewState;

ViewState get viewState => _viewState;

setViewState(ViewState viewState) {
_viewState = viewState;
notifyListeners();
}

AuthState _authState;

AuthState get authState => _authState;

setAuthState(AuthState authState) {
_authState = authState;
notifyListeners();
}
}

Here we have created two methods to change the state. setViewState method is used to switch the ViewState from Idel to Busy and vice-versa. setAuthState method is used to switch theAuthState from SignInto SignUpand vice-versa.

Now create a AuthModel class that extends BaseModel . This class will contain all the auth methods.

authModel.dart file

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_chat_app/enum/appState.dart';

import 'baseModel.dart';

class AuthModel extends BaseModel {
FirebaseAuth firebaseAuth = FirebaseAuth.instance;

void createNewUser(String email, String password) async {
setViewState(ViewState.Busy);
await firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
setViewState(ViewState.Ideal);
}

void signIn(String email, String password) async {
setViewState(ViewState.Busy);
await firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
setViewState(ViewState.Ideal);
}

void logOut() async {
setViewState(ViewState.Busy);
await firebaseAuth.signOut();
setViewState(ViewState.Ideal);
}
}

The above class will be used to provide the various methods that will handle the authentication of our app. Now we will make all the methods that will be used to handle all the UI changes when the user will switch between the sign-in and sign-up option.

authStateModel.dart file

import 'package:flutter/cupertino.dart';
import 'package:flutter_chat_app/enum/appState.dart';
import 'package:flutter_chat_app/model/authModel.dart';
import 'package:flutter_chat_app/model/baseModel.dart';

class AuthStateModel extends BaseModel {
switchAuthenticationState(AuthModel authModel) {
authModel.authState == AuthState.SignIn
? authModel.setAuthState(AuthState.SignUp)
: authModel.setAuthState(AuthState.SignIn);
}

switchAuthenticationMethod(
AuthModel authModel,
TextEditingController emailController,
TextEditingController passwordController,
) {
authModel.authState == AuthState.SignIn
? authModel.signIn(
emailController.text,
passwordController.text,
)
: authModel.createNewUser(
emailController.text,
passwordController.text,
);
}

switchAuthenticationText(AuthModel authModel) {
return authModel.authState == AuthState.SignIn ? "Sign In" : "Sign Up";
}

switchAuthenticationOption(AuthModel authModel) {
return authModel.authState == AuthState.SignIn
? "Create account ??"
: "Already registered ??";
}
}

Till here we have made all the required methods that will be used to update the UI of different screens. Now we will create a BaseView class that is used to update the UI, pass the model data that we have made earlier.

BaseView takes a builder function that takes BuildContext, Model, and a Widget as a parameter.

BaseView widget can only be used for the model class that extends BaseModel.

baseView.dart file

import 'package:flutter/material.dart';
import 'package:flutter_chat_app/locator.dart';
import 'package:flutter_chat_app/model/baseModel.dart';
import 'package:provider/provider.dart';

class BaseView<T extends BaseModel> extends StatefulWidget {
final Widget Function(BuildContext context, T model, Widget child) builder;

BaseView({
@required this.builder,
});

@override
_BaseViewState<T> createState() => _BaseViewState<T>();
}

class _BaseViewState<T extends BaseModel> extends State<BaseView<T>> {
T model = locator<T>();

@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<T>.value(
//builder: (context) => model,
child: Consumer<T>(builder: widget.builder),
//notifier: model,
value: model,
);
}
}

Let’s build the app UI

landingPage.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_app/model/authModel.dart';
import 'package:flutter_chat_app/ui/authPage.dart';

import 'package:flutter_chat_app/ui/baseView.dart';
import 'package:flutter_chat_app/ui/homePage.dart';

// ignore: must_be_immutable
class LandingPage extends StatelessWidget {
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();

@override
Widget build(BuildContext context) {
return BaseView<AuthModel>(
builder: (context, authModel, child) => StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
return snapshot.hasData
? HomePage()
: AuthPage(
emailController: emailController,
passwordController: passwordController,
authModel: authModel,
);
}),
);
}
}

authPage.dart file

import 'package:flutter/material.dart';
import 'package:flutter_chat_app/enum/appState.dart';
import 'package:flutter_chat_app/model/authModel.dart';
import 'package:flutter_chat_app/model/authStateModel.dart';
import 'package:flutter_chat_app/ui/baseView.dart';

class AuthPage extends StatelessWidget {
final TextEditingController emailController;
final TextEditingController passwordController;
final AuthModel authModel;

AuthPage({
@required this.emailController,
@required this.passwordController,
@required this.authModel,
});

@override
Widget build(BuildContext context) {
return BaseView<AuthStateModel>(builder: (context, authStateModel, __) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(20),
child: Center(
child: Column(
children: [
SizedBox(
height: 200,
),
TextFormField(
decoration: InputDecoration(hintText: "Email"),
controller: emailController,
),
TextFormField(
controller: passwordController,
decoration: InputDecoration(hintText: "Password"),
),
authModel.viewState == ViewState.Busy
? CircularProgressIndicator()
: RaisedButton(
child: Text(
authStateModel.switchAuthenticationText(authModel)),
color: Colors.cyanAccent,
onPressed: () {
authStateModel.switchAuthenticationMethod(
authModel, emailController, passwordController);
}),
InkWell(
onTap: () {
authStateModel.switchAuthenticationState(authModel);
},
child:
Text(authStateModel.switchAuthenticationOption(authModel)),
),
],
),
),
),
);
});
}
}

homePage.dart file

import 'package:flutter/material.dart';
import 'package:flutter_chat_app/model/authModel.dart';
import 'package:flutter_chat_app/ui/baseView.dart';

class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BaseView<AuthModel>(
builder: (context, model, __) => Scaffold(
body: Center(
child: RaisedButton(
color: Colors.cyanAccent,
child: Text("Log Out"),
onPressed: () {
model.logOut();
},
),
),
),
);
}
}

Register all the services with the locator

locator.dart file

import 'package:flutter_chat_app/model/authModel.dart';
import 'package:flutter_chat_app/model/authStateModel.dart';
import 'package:flutter_chat_app/model/baseModel.dart';
import 'package:get_it/get_it.dart';


final locator = GetIt.instance;

void setupLocator(){
locator.registerLazySingleton(() => BaseModel());
locator.registerLazySingleton(() => AuthModel());
locator.registerLazySingleton(() => AuthStateModel());
}

Initialize the setupLocator() method inside your main function

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
setupLocator();
runApp(MyApp());
}

GitHub Link

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


Thanks for reading this article ❤

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

Clap 👏 If this article helps you.

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

From Our Parent Company Aeologic

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

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

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

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

GridView List Widget In Flutter

0

In this blog, I will talk about the GridView List widget in a flutter by implementing a demo of the GridView List widget in your flutter applications. Now let’s start.


Table of Contents :

Flutter

GridView List widget

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single code base in record time ”

GridView List widget:

GridView Flutter has a widget that. Which displays the item in 2D. As its name suggests. We then use it. When we have to show the grid’s form items. We can tap on them. And go to another page. In this, we can take image text icon etc. as per our requirement.GridView widget is also considered to be scrollable. Because it is scrollable. To see an example of a grid view, we have many such apps like an e-commerce app such as snapdeal, etc. in which an example will be found.

GridView widget individually it has four more options.

  1. GridView.count
  2. GridView.builder
  3. GridView.custom
  4. GridView.extent

First of all, the following property is important to understand when we implement the grid view widget.

  • scrollDirection: Axis.Vertical or Axis.Horizontal. We can change the direction vertical and horizontal.
  • physics: We use scrolling to scroll the item. The utility scrolls from the list end of the list to the beginning.
  • shrinkWrap: If shrinkwrap is false then the item takes up more space to scroll. which is not good, This causes memory loss. And reduce the performance app. So we set it to avoid memory leakage while scrolling.
  • padding: It is used to specify the space around the whole list of widgets..
  • crossAxisSpacing: The crossAxisSpacing use to specify the number of pixels between widgets to all the children listed in the cross axis.
  • crossAxisCount: It is used to specify the number of columns in a grid view.
  • mainAxisSpacing: The crossAxisSpacing use to specify the number of pixels between widgets to all the children listed in the main axis.

Demo Module :

Code Implement :

GridView.count:

GridView.count is the most commonly used grid layout. Because we already know the size of the grid. The GridView count has a required end, known as the crossAxisCount.The essential property in the GridView is taken in the grid SliverGridDelegateWithFixedCrossAxis It is known in the same way as the crossAxisCount.This is obviously the most common.

Let us understand this with the help of a reference.

GridView.count(
crossAxisCount: 2,
childAspectRatio: (2 / 1),
crossAxisSpacing: 5,
mainAxisSpacing: 5,
//physics:BouncingScrollPhysics(),
padding: EdgeInsets.all(10.0),
children: items
.map(
(data) => GestureDetector(
onTap: () {
Navigator.of(context).pushNamed(RouteName.GridViewBuilder);
},
child: Container(
padding: const EdgeInsets.all(16),

// margin:EdgeInsets.symmetric(vertical: 5, horizontal: 5),
//color:data.color,
color: RandomColorModel().getColor(),
child: Column(
children: [
Icon(
data.icon,
size: 25,
color: Colors.black,
),
Text(data.title,
style: TextStyle(fontSize: 18, color: Colors.black),
textAlign: TextAlign.center)
],
),
)),
)
.toList(),
),
-----------------------------------------------------------
class RandomColorModel {
Random random = Random();
Color getColor() {
return Color.fromARGB(random.nextInt(300), random.nextInt(300),
random.nextInt(300), random.nextInt(300));
}
}

GridView.builder:

We use the GridView.builder when we want to make a big item grid list with a large number of children you can displays data dynamically or data on demand can be shown. Then we can use GridView.builder.

The following are 3 common features of GridViewbuilder.

  1. itemCount: The itemCount is used to define the amount of list item data.
  2. gridDelegate: The gridDelegate determines the divider. Its argument must not be null.
  3. itemBuilder (BuildContext context, int index): The gridViewBuider we use is used to create the item that is displayed on the grid view.

Let us understand this with the help of a reference.

GridView.builder(
itemCount:items.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: MediaQuery.of(context).orientation ==
Orientation.landscape ? 3: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: (2 / 1),
),
itemBuilder: (context,index,) {
return GestureDetector(
onTap:(){
Navigator.of(context).pushNamed(RouteName.GridViewCustom);
},
child:Container(
color: RandomColorModel().getColor(),
child: Column(
mainAxisAlignment:MainAxisAlignment.spaceEvenly,
children: [
Icon(items[index].icon),
Text(items[index].title,style: TextStyle(fontSize: 18, color: Colors.black),
textAlign: TextAlign.center),
],
),
),
);
},
)
-----------------------------------------------------------
class RandomColorModel {
Random random = Random();
Color getColor() {
return Color.fromARGB(random.nextInt(300), random.nextInt(300),
random.nextInt(300), random.nextInt(300));
}
}

GridView.custom :

Grid view is custom. It creates its own custom grid view. All property is the same. It has two essential assets. Which need to be defined using GridDevigate, GridDelegate, and ChildDelegate. Let us discuss Childelgate. Childelgate takes it in two different types of slivers.

  1. SliverChildListDelegate.
  2. SliverChildBuilderDelegate.

This is another way to show both the data or the length of the data. SliverChildListDelegate in which the specified number can specify the number of children. In SliverChildBuilderDelegate we can display many items.

Let us understand this with the help of an reference.

GridView.custom(
padding: EdgeInsets.all(10.0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: (2 / 1),
crossAxisSpacing: 5,
mainAxisSpacing: 5,
),
childrenDelegate: SliverChildListDelegate(

items.map((data) =>
GestureDetector(
onTap: (){
Navigator.of(context).pushNamed(RouteName.GridViewExtent);
},
child: Container(
padding: const EdgeInsets.all(16),
color: RandomColorModel().getColor(),
child: Column(
children: [
Icon(data.icon),
Text(data.title,
style: TextStyle(fontSize: 22, color: Colors.white),
textAlign: TextAlign.center)
],
),
)),

).toList(),
)),
-----------------------------------------------------------
class RandomColorModel {
Random random = Random();
Color getColor() {
return Color.fromARGB(random.nextInt(300), random.nextInt(300),
random.nextInt(300), random.nextInt(300));
}
}

GridView.extent:

GridView Extent property is used when we want to create a grid with custom extent values. It means each tile has a maximum cross-axis extent.

Let us understand this with the help of a reference.

GridView.extent(
childAspectRatio: (2 / 2),
crossAxisSpacing: 4,
mainAxisSpacing: 4,
padding: EdgeInsets.all(10.0),
maxCrossAxisExtent: 200.0,
children: List.generate(50, (index) {
return Container(
padding: EdgeInsets.all(20.0),
child: Center(
child: GridTile(
footer: Text(
'Item $index',
textAlign: TextAlign.center,
style:TextStyle(color:Colors.white,fontSize:15,fontWeight:FontWeight.bold),
),

child: Icon(Icons.access_alarm,
size: 40.0, color: Colors.white),
),
),
color: RandomColorModel().getColor(),
margin: EdgeInsets.all(1.0),
);
}),
),
-----------------------------------------------------------
class RandomColorModel {
Random random = Random();
Color getColor() {
return Color.fromARGB(random.nextInt(300), random.nextInt(300),
random.nextInt(300), random.nextInt(300));
}
}

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_gridview_demo/model/color_model.dart';
import 'package:flutter_gridview_demo/model/grid_items_model.dart';
import 'package:flutter_gridview_demo/route_names.dart';
class GridViewDemo extends StatefulWidget {
@override
_GridViewDemoState createState() => _GridViewDemoState();
}

class _GridViewDemoState extends State<GridViewDemo> {


List<GridListItems> items = [
GridListItems(color:Colors.green,title: 'Bicycle', icon: Icons.directions_bike),
GridListItems(color:Colors.pink[300],title:'Boat', icon: Icons.directions_boat),
GridListItems(color:Colors.pink[300],title: 'Bus', icon: Icons.directions_bus),
GridListItems(color:Colors.pink[300],title: 'Train', icon: Icons.directions_railway),
GridListItems(color:Colors.pink[300],title: 'Walk', icon: Icons.directions_walk),
GridListItems(color:Colors.pink[300],title: 'Contact', icon: Icons.contact_mail),
GridListItems(color:Colors.green,title: 'Bicycle', icon: Icons.directions_bike),
GridListItems(color:Colors.pink[300],title:'Boat', icon: Icons.directions_boat),
GridListItems(color:Colors.pink[300],title: 'Bus', icon: Icons.directions_bus),
GridListItems(color:Colors.pink[300],title: 'Train', icon: Icons.directions_railway),
GridListItems(color:Colors.pink[300],title: 'Walk', icon: Icons.directions_walk),
GridListItems(color:Colors.pink[300],title: 'Contact', icon: Icons.contact_mail),
GridListItems(color:Colors.green,title: 'Bicycle', icon: Icons.directions_bike),
GridListItems(color:Colors.pink[300],title:'Boat', icon: Icons.directions_boat),
GridListItems(color:Colors.pink[300],title: 'Bus', icon: Icons.directions_bus),
GridListItems(color:Colors.pink[300],title: 'Train', icon: Icons.directions_railway),
GridListItems(color:Colors.pink[300],title: 'Walk', icon: Icons.directions_walk),
GridListItems(color:Colors.pink[300],title: 'Contact', icon: Icons.contact_mail),
];

@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.count(
crossAxisCount: 2,
childAspectRatio: (2 / 1),
crossAxisSpacing: 5,
mainAxisSpacing: 5,
//physics:BouncingScrollPhysics(),
padding: EdgeInsets.all(10.0),
children: items.map((data) =>

GestureDetector(
onTap: (){
Navigator.of(context).pushNamed(RouteName.GridViewBuilder);
},
child: Container(
padding: const EdgeInsets.all(16),

// margin:EdgeInsets.symmetric(vertical: 5, horizontal: 5),
//color:data.color,
color: RandomColorModel().getColor(),
child: Column(
children: [
Icon(data.icon,size:25,color:Colors.black,),
Text(data.title,
style: TextStyle(fontSize: 18, color: Colors.black),
textAlign: TextAlign.center)
],
),
)),

).toList(),
),
);
}
}

Conclusion :

In this article, I have explained a GridView List widget demo, you can modify and experiment according to your own, this little introduction was from the GridView List widget from our side.

I hope this blog helps will provide you with sufficient information in Trying up the GridView List widget in your flutter project. In this demo explain the GridView List widget in flutter. So please try it.

❤ ❤ Thanks for reading this article ❤❤


From Our Parent Company Aeologic

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

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

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

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

Navigate with Named Routes in Flutter

0

Introduction :

Named Routes is the simplest way to navigate to the different screens using naming concepts. When a user needs multiple screens in an app depending on its need then we have to navigate from one screen to another and also return back many times back on the previous screen then it becomes a very hectic task, there we use a naming concept so as to remember screens with its name provided by the user and then we can directly access that route or page directly through Navigator.pushNamed() method.


Table of contents:

:: Create two routes(screen)

:: Defining the routes with names

:: Navigate from one route to another using Navigator.pushNamed()

:: Using static modifier to navigate to another page.

Create two Routes

Here above the code, we have created two routes or screens.

Defining the routes with names :

Note: We cannot use home property and initialRoute property both inside this MaterialApp as they both contradict each other.

We will navigate from one screen to another using Navigator.pushNamed() method.

Using static modifier to call naming routes :

If we use the routes method to navigate from one page to another with a naming concept then we have to remember the string that we have provided to its route. When there are multiple screens in an application then it becomes tough to remember each string. So we create one string datatype of it with the static modifier so that we can assign it by directly calling it through its class.

As you can see above we have used a static modifier with string datatypte to both our screen and assign it with the string variable.

Now we have to see how we will call these class in our routes::

As you can see now easily remember the routes by directly remembering its class name as shown above we have used Home.id and Second.id in place of using naming string routes and remembering each string name.

We can directly access it easily and can navigate from one page to another with the same name as provided above.


For more info visit down the link:

Navigate with named routes
In the Navigate to a new screen and back recipe, you learned how to navigate to a new screen by creating a new route…flutter.dev


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think are required…✔

From Our Parent Company Aeologic

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

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

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

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

Animated Align Widget in Flutter

0

In this blog, we will explore the Animated Align Widget in a flutter. We will be using some core functions available in a flutter. We will implement a demo of the Animated Align Widget in your flutter applications. So let’s get started.


Table of Contents :

Flutter

Animated Align Widget

Demo Module

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time ”.

Animated Align Widget:

The Animated Align Widget align that automatically positions the child’s position in a given period in a given alignment. And you can choose a period with a curve for the animation. And the widget will animate the alignment to the new target.

Let’s talk about some main constructors of the animated Align Widget. This widget has 3 properties. which do this work in our entire animation. As follows.

alignment(Alignment): where initially the child widget is placed.

curve(Curve): Easy curves are used to adjust the rate of changes in curve animation. This allows the speed to be slow and fast. there are some different-different types of options available.

duration(Duration): the Duration we can decide the time taken for a change of alignment according to ourselves.

Demo Module :

Code Implementation:

Create a new dart file calledanimated_align_demo inside the lib folder.

AnimatedAlign(
alignment: _alignment,
duration: Duration(seconds: 2),
curve: Curves.easeInOutBack,
child: SizedBox(
width: 100.0,
height: 100.0,
child: Image.asset(
'assets/images/pluginIcon.png',
height: 40,
)),
),

As I have understood above about the animated align widget. I have considered this as a demo in this screen. And a little code of this widget has been given above. As this screen has an image whose arrangement will go from Alignment.topRight to Alignment.bottomLeft. The duration time is also set as per our It has the option of the curve. There are many types of the curve. We have used the curves (Curves.easeInOutBack).

Code File :

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

import 'package:flutter/painting.dart';

class AnimatedAlignDemo extends StatefulWidget {
@override
_AnimatedAlignDemoState createState() => _AnimatedAlignDemoState();
}

class _AnimatedAlignDemoState extends State<AnimatedAlignDemo> {
static const _alignments = [
// Alignment.topLeft,
Alignment.topRight,
Alignment.bottomLeft,
// Alignment.bottomRight,
];

var _index = 0;

AlignmentGeometry get _alignment => _alignments[_index % _alignments.length];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.white,
title: Text(
'Animated Align',
style: TextStyle(
color: Colors.black,
),
),
centerTitle: true,
),
body: Container(
padding: EdgeInsets.all(15),
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
AnimatedAlign(
alignment: _alignment,
duration: Duration(seconds: 2),
curve: Curves.easeInOutBack,
child: SizedBox(
width: 100.0,
height: 100.0,
child: Image.asset(
'assets/images/pluginIcon.png',
height: 40,
)),
),
ButtonTheme(
minWidth: 100,
height: 50,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
child: RaisedButton(
color: Colors.purple.withOpacity(0.6),
onPressed: () {
setState(() {
_index++;
});
},
child: Text(
'Click Me',
style: TextStyle(
fontFamily: 'Roboto Medium',
fontSize: 15.0,
fontWeight: FontWeight.w600,
letterSpacing: 0.3,
color: Colors.white),
),
),
),
],
),
),
);
}
}

Conclusion :

In this article, I have explained an Animated Align Widget demo, you can modify and experiment according to your own, this little introduction was from the Animated Align Widget our side.

I hope this blog will provide you with sufficient information in Trying up the Animated Align Widget in your flutter project. So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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