Google search engine
Home Blog Page 49

ClipRRect & ClipPath In Flutter

0

In this blog, I will talk about creating a ClipRRect and Custom path using CustomClipper and use it in ClipPath in flutter application. In this app, we can circular the shape of any image using ClipRRect while we can create any type of shape using ClipPath. It will not contain any kind of package in it. We will implement a demo of the ClipRRect and ClipPath in a flutter in your flutter applications. Now let’s start.


Table of Contents :

Flutter

ClipRRect and ClipPath

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 

ClipRRect:

The ClipRRect widget is used to clip your child using a round import. It connects with the clippers family. The main function of the clippers is to print any part of the widget as per it’s a requirement. It is similar to ClipRect. It is used to clip the import part of the child widget. ClipRect has its own side per its requirement. We can do circulars. But Clippath is the one used to clip widgets in a customized fashion. We can do widgets as per our requirement. It has two Properties Clippers and ClipBehavior. Clippers what happens takes a custom clipper that defines how the text will be clipped and the clippings are clipped according to this option in the clip behaviour property.

Demo Module :

Code Implement :

1.ClipRRect:

This is a widget used to clip a round import. You can specify the radius of the corner in the borderRadius property of this widget. while you can not resize it in an image with rounded corners without this widget container widget decoration properties.

Create a new dart file calledcliprrect_demo inside the lib folder.

ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Image.asset(_img),
)

2.ClipPath:

We use ClipPath to customize the size of any image or container. The clippath has a clipper property that requires a custom clipper.

Create a new dart file calledclippath_demo inside the lib folder.

Container(
margin: EdgeInsets.only(left: 15, right: 15),
alignment: Alignment.center,
child: ClipPath(
clipper: ClipPathClass(),
child: SizedBox(
width: 320,
height: 240,
child: Image.asset(
_imageUrl,
fit: BoxFit.cover,
),
),
),
),

Creating a custom clipper requires creating a class. Which extends the CustomClipper<Path> and should override the two methods.

class ClipPathClass extends CustomClipper<Path> {
@override
Path getClip(Size size) {
var path = Path();
path.lineTo(0.0, size.height - 30);

var firstControlPoint = Offset(size.width / 4, size.height);
var firstPoint = Offset(size.width / 2, size.height);
path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy,
firstPoint.dx, firstPoint.dy);

var secondControlPoint = Offset(size.width - (size.width / 4), size.height);
var secondPoint = Offset(size.width, size.height - 30);
path.quadraticBezierTo(secondControlPoint.dx, secondControlPoint.dy,
secondPoint.dx, secondPoint.dy);

path.lineTo(size.width, 0.0);
path.close();

return path;
}

@override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}

When the custom clip needs to be updated, it is called the getClip method. and this method has a parameter that gives the value of width and height.

The shouldReclip method is called when providing a new instance of the class. If the new example has different information than the old one, it should be returned true or it is false.

As you can see above, the x- increases horizontally, and Y-axis increases downward.

lineTo:

Using this method one can cut the widget with a line from the given point . x and y are two destinations points where the line stops.

quadraticBeizerTo:

with the help of quadraticBeizer method, you can clip your widget with curves.we can draw a quadratic bezier curve using the control point and endpoint.

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_cliprrect_clipath_demo/route_names.dart';

class ClipRRectDemo extends StatefulWidget {
@override
_ClipRRectDemoState createState() => _ClipRRectDemoState();
}

class _ClipRRectDemoState extends State<ClipRRectDemo> {
double _height;
double _width;
String _img = 'assets/images/just_in2.jpg';

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue[300],
title: Text('ClipRRect'),
centerTitle: true,
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Center(
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Image.asset(_img),
)),
MaterialButton(
onPressed: () {
Navigator.of(context).pushNamed(RouteName.CliPathScreen);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0))),
height: _height / 18,
minWidth: _width,
elevation: 0,
color: Colors.blue[300],
padding: EdgeInsets.all(16.0),
child: Text('Next',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
fontFamily: 'Roboto Medium',
color: Colors.white,
)),
),
],
),
),
);
}
}

import 'package:flutter/material.dart';
import 'package:flutter_cliprrect_clipath_demo/clipath_class.dart';

class ClipPathDemo extends StatefulWidget {
@override
_ClipPathDemoState createState() => _ClipPathDemoState();
}

class _ClipPathDemoState extends State<ClipPathDemo> {
double _height;
double _width;

String _imageUrl = 'assets/images/just_in2.jpg';

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue[300],
title: Text('ClipPath'),
centerTitle: true,
),
body: Container(
margin: EdgeInsets.only(left: 15, right: 15),
alignment: Alignment.center,
child: ClipPath(
clipper: ClipPathClass(),
child: SizedBox(
width: 320,
height: 240,
child: Image.asset(
_imageUrl,
fit: BoxFit.cover,
),
),
),
),
);
}
}

Conclusion :

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

I hope this blog helps will provide you with sufficient information in Trying up the ClipRRect and Clippath 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.

S.O.L.I.D Principles In Dart

0

It’s an acronym for 5 design principles for writing code which is maintainable, scalable and easier to understand. These principles are given by Bob. C Martin (uncle bob) more familiar to the developer world.


Things To Understand Firstly :

What Problem these S.O.L.I.D principles solved?

  1. working with the legacy code.
  2. Re-reading the code multiple times to get to the part you need to change
  3. Hard to understand what the method does. jumping multiple methods of the same name
  4. spending a lot more time to fix a minor bug

Basically, we spend a lot more time reading than writing code.

1. Single Responsibility principle

As it’s clear from its name single responsible. A class should only be responsible for one thing that means a class could change for only one reason.

Let’s first see the bad practise in which maintenance is not pleasant. Because of all the things in one single place validation, getRequest, painting.

class Result
{

checkResult(int rollno)
{
bool isRollnoValidate = isRollnovalidate();
if(isRollnoValidate)
{

ResultModel resultModel = searchResult();
showResult(resultModel);
}
else{
return "Invalid rollno";
}

}

isRollnovalidate()
{

return true;
}

// get request
searchResult()
{
// return result;
}

//painting
showResult(ResultModel model)
{
// show result in pleasant way
}

}

class ResultModel
{

}

After applying the Single Responsibility principle

Now the developer can focus on the desired functionality.

info :: class Result is responsible for the flow.


class Result {
checkResult(int rollno) {
bool isRollnoValidate = Validate().isRollnovalidate();
if (isRollnoValidate) {
ResultModel resultModel = NetworkApi().searchResult();
Printing().showResult(resultModel);
} else {
return "Invalid rollno";
}
}
}

class Validate {
// this is responsible for validate
isRollnovalidate() {
return true;
}
}

class ResultModel {}

class Printing {
// this class is responsible for printing
showResult(ResultModel model) {
// show result in pleasant way
}
}

class NetworkApi {
// this class is responsible for fetching result
searchResult() {
return ResultModel();
}
}

2. OPEN-CLOSED PRINCIPLE

An entity should be open for extensions but closed for modification

It states that for good practise you should be able to add new features without modifying the existing code.

Let’s first see the bad practice. In this, if we need to mechanical branch result feature then we need to edit the existing code.

class Result
{
mechanicalCheckResult()
{
// some code
}

civilCheckResult()
{
// some code
}

}

After applying Open CLOSED PRINCIPLE. In this, we create a class for adding new functionality.


abstract class Result {
checkResult();
}

class ComputerScience implements Result {
@override
checkResult() {
// some code
}
}

class Civil implements Result {
@override
checkResult() {
// some code
}
}

class Mechanical implements Result {
@override
checkResult() {
// some code
}
}

3. Liskov Substitution Principle

It means how good is your design from abstraction perspective

The architecture guarantee that the subclass will maintain the logic correctness of code.Basically prefer composition (with interfaces) over inheritance

As above let’s first see bad practice

 abstract class Result {
checkResult();

codingTestResult();
}

class MechanicalBranch extends Result {
@override
checkResult() {
// some code
}

/*
* Here it is logically incorrect
* */
@override
codingTestResult() {
// some code
}
}

class ComputerScienceBranch extends Result {
@override
checkResult() {
// some codet
}

@override
codingTestResult() {
// some code
}
}

After Applying the Liskov Substitution Principle

abstract class OfflineResult {
checkResult();
}

abstract class CodingResult {
codingTestResult();
}

class MechanicalBranch implements OfflineResult {
@override
checkResult() {
// some code
}
}

class ComputerScienceBranch implements OfflineResult, CodingResult {
@override
checkResult() {
// somecode
}

@override
codingTestResult() {
// somecode
}
}

4. Interface Segregation Principle

It states that no client should be forced to depend on methods it does not use.

Basically client should never depend on anything more than the method its calling.

Bad practiCe :

abstract class Result {
checkResult();

codingTestResult();
}

class MechanicalBranch implements Result {
@override
checkResult() {
// some code
}

/*
* Here we exposed client with the method which none of his * business
* */
@override
codingTestResult() {
// some code
}
}

class ComputerScienceBranch implements Result {
@override
checkResult() {
// some codet
}

@override
codingTestResult() {
// some code
}
}

After applying the Interface Segregation Principle :

abstract class OfflineResult {
checkResult();
}

abstract class CodingResult {
codingTestResult();
}

class MechanicalBranch implements OfflineResult {
@override
checkResult() {
// some code
}
}

class ComputerScienceBranch implements OfflineResult, CodingResult {
@override
checkResult() {
// somecode
}

@override
codingTestResult() {
// somecode
}
}

5. Dependency Inversion Principle

Abstractions should not depend on details(concrete implementations). They should depend on abstractions.

Basically, you should able to change the implementation(background or low level code) without altering the high-level code(actual class you interact to).

Its good to extending a abstract class or interface but reverse (means with no abstract method) is a bad practise.

Depending on abstractions gives the freedom to be independent of the implementations. Let’s dig into it.

abstract class Payment {
payment();
}

class PaymentViaCreditCard implements Payment
{
@override
payment() {
// some code
}
}

class PaymentViaDebitCard implements Payment
{
@override
payment() {
// some code
}
}

class PaymentViaBhimUPI implements Payment
{
@override
payment() {
// some code
}
}


class Checkout
{
// our checkout class knows nothing about how payment works
// its knows pay.payment() is paying method
checkOut(Payment pay)
{
pay.payment();
}
}

I highly recommend watching this video. That’s the minimum thing I can do to express my gratitude.

Conclusion :

Don’t get trapped by Solid

: S.O.L.I.D Principles are principles, not rules

: Always use common sense while applying this. Your goal is to achieve to make your code maintainable, easy to extend.

: Avoid over- fragmenting your code for the sake of SRP or S.O.L.I.D

: Don’t try to achieve S.O.L.I.D, use S.O.L.I.D to achieve maintainability. It’s a tool, not your goal

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!

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.