Google search engine
Home Blog Page 50

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.

Implementing Phone calls In Flutter apps

0

Flutter is really a fantastic tool to build mobile apps. Flutter is a free and open-source tool to develop mobile, desktop, web apps with a single code base. The technical architecture of flutter apps is a much easier, clean, and precise code structure. The community of flutter developer is constantly growing, helping us to provide a better experience and by developing various plugins. Plugins are great, help us to implement various functionality with lesser code and time.

The plugin page provides us an insight into the package quality. We must always prefer to use the package that has better maintenance, continuous improvement, good responses, and Flutter Favourite.


To implement the phone call functionality we need to use the bellow package:

url_launcher | Flutter Package
Flutter plugin for launching a URL on Android and iOS. Supports web, phone, SMS, and email schemes.pub.dev

flutter_phone_direct_caller | Flutter Package
A simple plugin to call a number directly from the app, without going to the phone dialer. Permission request is handled by…pub.dev

  • url_launcher package will be used to implement phone call using the default app of your mobile phone. This package will auto direct the phone to the default phone call making app and open the dialer screen to make the call.
  • flutter_phone_direct_caller package is not the best package but we will learn how to implement direct phone calls directly from our phone without the intermediate dialer.

Install the following dependencies inside your pubspec.yaml file:

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^latest version
flutter_phone_direct_caller: ^latest version
url_launcher: ^
latest version

Making Phone Calls using the flutter_phone_direct_caller:plugin

To implement the phone call using this plugin is really very easy. This package provides us FlutterPhoneDirectCaller class that provides us callNumber() method that takes a phone number.

_callNumber(String phoneNumber) async {
String number = phoneNumber;
await FlutterPhoneDirectCaller.callNumber(number);
}

RaisedButton:

RaisedButton(
child: Text("Call"),
onPressed: () {
_callNumber(textEditingController.text);
},
)

Making Phone Calls using the url_launcher:plugin

This package provides us launch(URL) method that takes an URL with schema. Scheme is very essential as it directs the URL. In the case of phone calls, we use ‘tel:’ schema.

_launchPhoneURL(String phoneNumber) async {
String url = 'tel:' + phoneNumber;
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Here we have made a simple method that takes a String phoneNumber, this method will check whether the URL is correct or not if yes then the launch method will launch it else it will throw an error.

Pass this method inside the onPressed property of the above RaisedButton

RaisedButton(
child: Text("Call"),
onPressed: () {
_launchPhoneURL(textEditingController.text);
},
)

Full code:

import 'package:flutter/material.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
TextEditingController textEditingController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: TextFormField(
keyboardType: TextInputType.phone,
controller: textEditingController,
onSaved: (phoneNumber) {
textEditingController.text = phoneNumber;
},
),
),
RaisedButton(
child: Text("_launchPhoneURL"),
onPressed: () {
_launchPhoneURL(textEditingController.text);
},
),
RaisedButton(
child: Text("_callNumber"),
onPressed: () {
_callNumber(textEditingController.text);
},
)
],
),
);
}
}

_callNumber(String phoneNumber) async {
String number = phoneNumber;
await FlutterPhoneDirectCaller.callNumber(number);
}

_launchPhoneURL(String phoneNumber) async {
String url = 'tel:' + phoneNumber;
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Demo:


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

Ignore Pointer Widget In Flutter

0

Today mobile users expect their apps should have a beautiful UI design, smooth animations, and great performance. To achieve this developer needs to create a new feature without compromising on quality and performance. That’s why Google build Flutter.

In this article, I’ll explain how to use the IgnorePointer widget in Flutter 


Table of Contents :

Flutter — Introduction

Widgets — Introduction

IgnorePointer

Code Implementation

Code File

Conclusion


What is Flutter?

Flutter is Google’s open-source UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase.

Widgets

Widget is a way to declare UI in a flutter. Flutter provides several widgets that help you build apps that follow Material Design that takes inspiration from React. The central idea is that you build your UI out of widgets. Widgets describe what their view should look like given their current configuration and state.

IgnorePoiner

IgnorePointer is a built-in widget that prevents their children’s widget from pointer-events like tapping, dragging, scrolling, and hover. This widget ignores the pointer-events without terminating them.

Constructor: Creates a widget that is invisible to hit testing.

Properties

ignoring -> takes bool value and decides whether to ignore pointer event or not
ignoringSemantics -> Whether the semantics of this widget is ignored when compiling the semantics tree

Code Implementation

Let’s move on the coding part

This widget is used to prevent unnecessary touch of UI. It is very simple just wrap your widget inside the IgnorePointer widget.

First, we create a widget and wrap it into the IgnorePointer widget.

In this snippet, we are using a button that is wrapped with the IgnorePointer widget. When ignoring is true RaisedButton can’t perform any action. So, IgnorePointer ignoring all the pointer-events. The code is shown below.

Code File

import 'package:flutter/material.dart';

class MyIgnorePointer extends StatefulWidget {
@override
_MyIgnorePointerState createState() => _MyIgnorePointerState();
}

class _MyIgnorePointerState extends State<MyIgnorePointer> {
bool _isIgnore = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Ignore Pointer Demo'),
),
body: Builder(
builder: (context) => Center(
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IgnorePointer(
ignoring: _isIgnore,
child: Column(
children: <Widget>[

Container(
width: MediaQuery.of(context).size.width,
height: 55,
child: RaisedButton(
child: Text('Click me',style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold
),),
onPressed: (){

showAlertDialog(context);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(8)),
),
color: Colors.blue,

),
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Enable Ignore Pointer?'),
Switch(
value: _isIgnore,
onChanged: (bool value) {
setState(() {
_isIgnore = value;
});
}),
],
),
],
),
),
),
),
);
}

showAlertDialog(BuildContext context) {

// set up the button
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.pop(context);
},
);

// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Message"),
content: Text("Button is pressed."),
actions: [
okButton,
],
);

// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}}

Conclusion

In this article, I have explained the IgnorePointer widget demo, which you can modify and experiment with according to your own. This little introduction was about to prevent user touch of UI.

I hope this blog will provide you with sufficient information in trying up IgnorePointer Widgets in your flutter projects. We will show to prevent the UI from user interaction, some properties using in “ignoring”, and make a demo program for working IgnoringPointer in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

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

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

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

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

TabBar Widget in Flutter

0

In this blog, We are going to discuss about the TabBar. How the TabBar works. And why we use Tabbar. and we will discuss how to display a horizontal row of tabs and display a widget that corresponds to the currently selected tab. We will explain all these in a demo. Now let’s start.


Table of Contents :

Flutter

TabBar

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 code base in record time ”

TabBar:

The TabBar is used mainly to navigate different screens in one screen. This is what you need first to build the TabBarController. There are two ways to do this. By using the DefaultTabbarController or by creating a TabController.

We mainly need 3 components to create this TabBar.

  1. Create a TabController.
  2. Create the tabs.
  3. TabBarView.

TabController: The TabController is used to control the movement between created tabs.

TabController(length: list.length, vsync: this);

Create Tabs: We need a scaffold to create a TabBar. It should have a bottom attribute. Tabs are a list of forms. This means that it is necessary to have as many tabs as you are making.

bottom: new TabBar(
tabs: <Widget>[
Tab(icon: Icon(Icons.cake)),
Tab(icon: Icon(Icons.android)),
Tab(icon: Icon(Icons.phone_android)),
],
),

TabView: When we press any TabBar using the TabView, we see a new page.

For Example, We can see the WhatsApp App as if we click any tab, then a different page appears on the different tabs.

Demo Module:

Code Implementation:

There are two buttons in this screen, which on clicking will navigate us to the result of the tabbar on the screen.

DefaultTabBarController:

In this screen, we have used the DefaultTabBarController for TabBar. The TabBar DefaultTabBarController is an inherited widget. It is used to share a TabController with a TabBar or TabBarView.If you are using the stateless widget. The best approach is to use DefaultTabController.And in TabBar we have used 3 different icons. On Tap its icon, we have shown different view in TabbarView.

Let us understand this with the help of a reference.

DefaultTabController(
length: 3,
child: new Scaffold(
appBar: new AppBar(
title: new Text("TabBar Widget"),
bottom: new TabBar(
tabs: <Widget>[
Tab(icon: Icon(Icons.cake)),
Tab(icon: Icon(Icons.android)),
Tab(icon: Icon(Icons.phone_android)),
],
),
),
body: new TabBarView(
children: <Widget>[
Container(
color: Colors.deepOrangeAccent,
child: new Center(
child: new Text(
"Cake",
style: textStyle(),
),
),
),
],
),
),
)

The DefaultTabController results can be seen in the image.

Custom TabController:

In this screen, a custom TabController is used in the TabBar. For This stateful widget is used.

Let us understand this with the help of a reference.

First of all create a Stateful Widget.which should be SingleTickerProviderStateMixin.

class CustomTabBarDemo extends StatefulWidget {
@override
_CustomTabBarDemoState createState() => _CustomTabBarDemoState();
}

class _CustomTabBarDemoState extends State<CustomTabBarDemo> with SingleTickerProviderStateMixin {
}

To create a tab in it, create a tab list and create an object of its TabController.

List<Widget> list = [
Tab(icon: Icon(Icons.android)),
Tab(icon: Icon(Icons.add_shopping_cart)),
Tab(icon: Icon(Icons.card_giftcard)),
Tab(icon: Icon(Icons.phone_android)),
];
//////////////////////////////////////////////
TabController _tabController;

Initalize the TabController inside the initState() method and also override it in the dispose() method.

@override
void initState() {
super.initState();
_tabController =
TabController(length:list.length, vsync: this);// initialise it here
}

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

The CustomTabBar results can be seen in the image.

Code File:

I am posting the code of both examples. Which I have created as a demo in this blog.

DefaultTabBarController Code File:

import 'package:flutter/material.dart';
class TabBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
textStyle() {
return TextStyle(color: Colors.white, fontSize: 30.0);
}
return new DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title:Text("TabBar Widget"),
bottom:TabBar(
tabs: <Widget>[
Tab(icon: Icon(Icons.cake)),
Tab(icon: Icon(Icons.android)),
Tab(icon: Icon(Icons.phone_android)),
],
),
),
body:TabBarView(
children: <Widget>[
Container(
color: Colors.deepOrangeAccent,
child:Center(
child:Text(
"Cake",
style: textStyle(),
),
),
),
Container(
color: Colors.blueGrey,
child:Center(
child:Text(
"Android",
style: textStyle(),
),
),
),
Container(
color: Colors.teal,
child:Center(
child:Text(
"Mobile",
style: textStyle(),
),
),
),
],
),
),
);
}
}

Custom TabBarController Code File:

import 'package:flutter/material.dart';
class CustomTabBarDemo extends StatefulWidget {
@override
_CustomTabBarDemoState createState() => _CustomTabBarDemoState();
}

class _CustomTabBarDemoState extends State<CustomTabBarDemo> with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
super.initState();
_tabController =
TabController(length:list.length, vsync: this);// initialise it here
}

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

List<Widget> list = [
Tab(icon: Icon(Icons.android)),
Tab(icon: Icon(Icons.add_shopping_cart)),
Tab(icon: Icon(Icons.card_giftcard)),
Tab(icon: Icon(Icons.phone_android)),
];

textStyle() {
return TextStyle(color: Colors.black, fontSize:20.0);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: _tabController,
isScrollable: true,
tabs:list,
indicator: UnderlineTabIndicator(
borderSide: BorderSide(width: 2.0,color:Colors.white),
insets: EdgeInsets.symmetric(horizontal:0.0)
),


// / indicatorPadding: EdgeInsets.all(0.0),
indicatorWeight: 4.0,
labelPadding: EdgeInsets.only(left:30.0, right:30.0),
),
title: Text('tabBar'),

),

body: TabBarView(
controller: _tabController,
children: [
Center(
child: Text(
'Cake',
style: textStyle(),
)),
Center(
child: Text(
'Cart',
style: textStyle(),
)),
Center(
child: Text(
'GiftCard',
style: textStyle(),
)),
Center(
child: Text(
'Phone',
style: textStyle(),
)),
],
),

);
}
}

Conclusion :

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

I hope this blog helps will provide you with sufficient information in Trying up the TabBar List widget in your flutter project. In this demo explain the TaBar 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.

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.

Local Authentication in Flutter — Passcode

Hello and welcome to my new blog on Passcode authentication. In this blog, we shall learn and explore how we can implement a simple local authentication using a passcode. This type of authentication is much secure and private also it is extremely fast. Another user how doesn’t know your passcode can’t access your app content directly. This type of authentication removes the server-side errors and provides clean checkout to access the app.

Please give it a try by yourself and try to find out how we can implement this type of functionality with ease. Hopefully, we will require some pub packages as well so please try to find out by yourself which package might help to implement this functionality.

Demo Module:

So what your thought on this? please share your approach on this functionality. Now here is mine, so let’s go……


The packages that we are going to use are:

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

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

shared_preferences | Flutter Package
Wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on…pub.dev

  • We will use the provider package for state management.
  • shared_preferences package us various methods to store our data inside our app locally and safely.
  • get_it help us to register our services in a very simple and easy way.

State management technique used in this module

Before getting into the functionality part let’s first learn the state management structure of the app.

  • We have created a file baseModel.dart that contains a BaseModel class that extends ChangeNotifier . In this file, we will write all the common methods that we will use throughout our app such as implementing circular progress indicator when and method is awaited.
  • For each screen, we will create a separate file that will contain all the code that will handle all the methods that will provide the data for that particular screen from the internet server or local server. Each file will extends BaseModel in general ChangeNotifier.
  • We will create a separate widget that we will use to access the provider methods or class.BaseView can only be used for the model class that extends BaseModel .
  • Please go through the bellow blogs for a better understanding of this state management technique.

Flutter and Provider Architecture using Stacked
In this series, we will be taking an extensive look at how I will architect the applications for my clients moving…www.filledstacks.com

Let’s start our code:

  • Create a baseModel.dart file that extends ChangeNotifier.
import 'package:flutter/material.dart';

class BaseModel extends ChangeNotifier {}
  • Create a sharedPrefs.dart file that will contain the passCode uploading and fetching code from the local store and this model will be used for the passcode check out screen.

Uploading the passCode value:

setPassCode(int passCodeValue) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setInt('passCode', passCodeValue);
}

sharedPreferences is an object of SharedPreferences that will provide us access to all the methods. This method takes a passCodeValue int that will be stored under the ‘passCode' key.

sharedPreferences.setInt('passCode', passCodeValue);

setInt method creates a passCode key in the app local storage and store the passCodeValue in it.

Fetching the passCode value:

First, create a variable that will store the fetched value of the passCode from the local server.

int _passCode;

int get passCode => _passCode;

passCode is a getter of _passCode that get and store the value of _passCode whenever it is changed.

getPassCode method is used to fetch the value of passCode . To get the value of the passCode key SharedPreferences provides us getInt method.

getPassCode() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
int code = sharedPreferences.getInt('passCode');
print("**************" + code.toString());
_passCode = code;
notifyListeners();
}

Full File:

import 'package:local_passcode_auth/baseModel.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefs extends BaseModel {
int _passCode;

int get passCode => _passCode;

setPassCode(int passCodeValue) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setInt('passCode', passCodeValue);
//upload the passCodeValue
  }

getPassCode() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
int code = sharedPreferences.getInt('passCode');
//fetch the passCode value
print("**************" + code.toString());
_passCode = code;
notifyListeners();
//informs the passCode getter that the value has been changed and it will update the ui wherever it is used.
}
}
  • Regester all the models using the get_it

locator.dart file:

import 'package:get_it/get_it.dart';
import 'package:local_passcode_auth/sharedPrefs.dart';

import 'baseModel.dart';

final locator = GetIt.instance;

void setupLocator() {
locator.registerLazySingleton(() => BaseModel());
locator.registerLazySingleton(() => SharedPrefs());
}
  • initialize the setupLocator() method inside the main method
void main() {
setupLocator();
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
darkTheme: ThemeData(),
home: MyApp(),
),
);
}

baseView.dart file:

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

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

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

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

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

@override
void initState() {
if (widget.onModelReady != null) {
widget.onModelReady(model);
}
super.initState();
}

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

checkoutPage.dart file:

This page is our main page that will contain a simple TextField that will take the passCode from the user and verify it with the fetched Passcode, if both the values are the same then we will navigate it to the HomePage .

Here we will require the sharedPrefs fetch and upload methods that we have created in sharedPrefs.dart file.

To use SharedPrefs class we need to use the BaseView class. BaseView class provides us builder, onModelReady property to build the builder of the Consumer and onModelReady will be used to initialize the methods or values inside the initStatemethod.

Data Flow of this file:

  • When this Widget is called inside the init state model.setPassCode(1234), model.getPassCode() will be called so that the passCode getter in the sharedPrefs.dart can get the value of the passcode. BaseView provides us onModelReady method to initialize the methods inside the initState() method.
  • Now we can use use the value of the passCode getter inside our builder.
  • We have created a TextField that will take the value of passCode form the user and when the user will click on the right arrow button then the onPressed property of icon will check the condition if it is true then the user will be navigated to the HomePage.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:local_passcode_auth/baseView.dart';
import 'sharedPrefs.dart';
import 'homePage.dart';

// ignore: must_be_immutable
class CheckoutPage extends StatelessWidget {
TextEditingController textEditingController = TextEditingController();

@override
Widget build(BuildContext context) {
return BaseView<SharedPrefs>(
onModelReady: (model) {
model.setPassCode(1234);
model.getPassCode();
},
builder: (context, model, child) => Scaffold(
backgroundColor: Colors.black,
body: Padding(
padding: const EdgeInsets.all(10),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: TextField(
controller: textEditingController,
decoration: InputDecoration(
suffixIcon: IconButton(
onPressed: () {
if (model.passCode.toString() ==
textEditingController.text) {
Navigator.pop(context);
Navigator.of(context).push(PageRouteBuilder(
pageBuilder:
(context, animation, anotherAnimation) {
return HomePage();
},
transitionDuration: Duration(milliseconds: 600),
transitionsBuilder: (context, animation,
anotherAnimation, child) {
animation = CurvedAnimation(
curve: Curves.easeIn, parent: animation);
return SlideTransition(
position: Tween(
begin: Offset(-1.0, 0.0),
end: Offset(0.0, 0.0))
.animate(animation),
child: ScaleTransition(
scale: animation,
child: child,
),
);
}));
} else
print("failed");

print("************+++" + model.passCode.toString());
},
icon: Icon(Icons.forward),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
),
labelText: "Enter PIN",
),
obscureText: true,
autofocus: true,
cursorColor: Colors.grey,
keyboardAppearance: Brightness.dark,
keyboardType: TextInputType.number,
),
)
],
),
),
),
),
);
}
}

GitHub File:

flutter-devs/local_passcode_auth
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!.

Improving Rendering Performance in Flutter App

In order to maintain app performance, we make every possible effort but any app’s performance relies on two main things which are time and space. The space-related issue is explained in my previous blog where I have explained how to reduce app size and make your app performant.

Rendering is the key factor that provides smoothness to the app and it depends on the fps.


You must be thinking about how no of frames per second can help in the app performance and you must have heard a lot about 60 fps and 16 milliseconds barries. So for information Human mind reacts according to the visual signals sent by the eyes and there is no concept of frames in this regard but the concept of motion has its own effect in this regard. By displaying images at a faster speed you can trick the mind into perceiving motion and here the concept of fps(Frames per second)comes into the effect. It means a concept of motion is a kind of hack of mind.

It needs a minimum of 10–12 frames per second when the human mind starts perceiving motion but it does not look smooth, 24 frames per second allow the human eye to see fluid motion but in movies and videos it takes at least 60 frames per second where a human mind easily feels a smooth motion with fluency.

So the formula would look like

1000ms / 60 frames = 16.666 ms/frame

It means you need to replace every frame in 16.66 milliseconds to do your work computing, input, network, and rendering if you are not able to do this you need to find out where your app lacks and where it needs improvement.

Identifying Performance

In order to identify the performance issue, you just need to open tools here you can identify the no of times the widget is rebuilding and where you need to correct or need to make some changes to your code.

Improve Rendering performance

If the performance is the issue rendering is the factor that comes first in the list we need to deal with, but flutter’s Skia engine takes care of it. Generally, if we are dealing with performance issues there are some common pitfalls

  • Rebuilding more of the UI in every frame

So try not to write code for the whole screen in a single Stateful Widget that may cause unnecessary UI building, you need to split code into smaller widgets and smaller build functions.

  • Building a large list of children directly and operating things up higher in the tree using setState().

So setState() affects apps rendering performance more than anything so instead of calling high up on the tree try to call it on the specific part of the subtree.

How to Improve Performance?

In order to improve build performance, there are some steps which we need to improve and some of them are

Controlling build()

  • Repetitive code and heavy work should be avoided in the build() method so the build() method can be invoked frequently when widgets are rebuilt.

Apply Effects when needed

Applying effects are always expensive because it causes or responsible to create saveLayer() behind the scenes.

Why is savelayer expensive?

Calling saveLayer() allocates an offscreen buffer. Drawing content into the offscreen buffer might trigger render target switches that are particularly slow in older GPUs.

Some rules need to be followed

  • Use the Opacity widget if it is necessary if you using it for a single image there are various options to doing so because For example, Container(color: Color.fromRGBO(255, 0, 0, 0.5)) is much faster than Opacity(opacity: 0.5, child: Container(color: Colors.red)).

Directly drawing an Image or Color with opacity is faster than using Opacity on top of them because Opacity could apply the opacity to a group of widgets and therefore a costly offscreen buffer will be used. Drawing content into the offscreen buffer may also trigger render target switches and such switching is particularly slow in older GPUs.

Clipping doesn’t call saveLayer() (unless explicitly requested with Clip.antiAliasWithSaveLayer) so these operations aren’t as expensive as Opacity, but clipping is still costly, so use with caution. By default, clipping is disabled (Clip.none), so you must explicitly enable it when needed.

Some widgets are costly because they call saveLayer() and are potentially costly

  • Shader Mask
  • color filter
  • chip
  • text

There are also some other widgets you may call instead such as to provide fading in an image we can call FadeInImage because it applies gradual opacity using GPU’S fragment shader. In order to provide a rounded corner, we should prefer a border-radius instead of clipping.

Rendering Grids and Lists lazily can help to build up the potion which is going to be seen firstly.

Manage Shader Compilation Jank

If any animation seems janky during the first run but after it works fine maybe this is an issue of shader compilation jank.

More deeply and technically, Shader is a set of code that runs on a GPU( Graphics processing unit). A smooth frame needs to be drawn within 16 milliseconds for a 60 fps display but during the compiling shader takes more time than it should take. it could be nearly a few hundred milliseconds and it causes tens of frames to be missed and drops the fps from 60 to 6.

How to sort it out?

As a Solution for this after the release of Flutter 1.20, Flutter provides command-line tools for developers and by this developers can collect shaders that might be needed for the end-users in the Skia Shader Language format. Once SkSL shader will be packaged into the app then it will automatically be pre-compiled when the end-user opens the app.

There are few commands to perform the action

Run the app with --cache-sksl turned on to capture shaders in SkSL:

flutter run --profile --cache-sksl

If the same app has been previously run without --cache-sksl, then the --purge-persistent-cache the flag may be needed:

flutter run --profile --cache-sksl --purge-persistent-cache

This flag removes older non-SkSL shader caches that could interfere with SkSL shader capturing. It also purges the SkSL shaders so use it only on the first --cache-sksl run.

Build the app with SkSL warm-up using the following, as appropriate:

Android

flutter build apk — bundle-sksl-path flutter_01.sksl.json

Ios

flutter build ios --bundle-sksl-path flutter_01.sksl.json

Conclusion

These are some techniques to improve rendering performance that may help to make the app performant. Sometimes animations, growing list, some widgets (generally call saveLayer()) make an app janky and more rendering so in order to maintain these things we must make focus on the points mentioned above.

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


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

Dismissble Widget in Flutter

0

Flutter widget is built using a modern framework. It is like a react. In this, we start with the widget to create any application. Each component in the screen is a widget. The widget describes this. of what his outlook should be given his present configuration and condition. Widget shows were similar to its idea and current setup and state.

In this article, we will Explore Dismissble Widget In Flutter. We will also implement a demo of the Dismissble, and describes his properties. and how to use them in your flutter applications. So let’s get started.


Table Of Contents:

Disimissble Widget

Code Implementation

Code File

Conclusion


Disimissble Widget:

A widget that we can drag and dismiss in the indicative direction. So you can wrap the widget as a child of unacceptable. The separable is usually used to wrap a list item so that it can be ruled out horizontally or vertically.

The Disimissble class provides some properties which we have described below.

  1. Background — At the time of dismissal in the background, you can set the background color of its item.
  2. Direction —The direction allows us to specify direction.
  3. onDismissed — OnDisimissed (onDismissed) is based on the important property.it is the callback function. It accepts one parameter of the design direction.

Demo Module:

In this demo module, we have a list item which contains some data. when we swipe the item. So the item gets deleted from the list.

Code Implementation:

In this screen, we have a list of items that we have done with the ItemBuilder method. And in this, we have used the Flutter Dismissible widget. It receives a method under onDismissed along with the DismissDirection.

Let us understand this with the help of a reference.

ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
return Dismissible(
onDismissed: (DismissDirection direction) {
setState(() {
data.removeAt(index);
});
},
secondaryBackground: Container(
child: Center(
child: Text(
'Delete',
style: TextStyle(color: Colors.white),
),
),
color: Colors.red,
),
background: Container(),
child: DissmbleLayoutCard(movie: data[index]),
key: UniqueKey(),
direction: DismissDirection.endToStart,
);
},
)

We have set the color for the background color. The Item which is red color visible in delete time.

Dismissible(
key: ValueKey(item),
background: Container(
color: Colors.red,
),
secondaryBackground: Container(
child: Center(
child: Text(
'Delete',
style: TextStyle(color: Colors.white),
),
),
color: Colors.red,
),
...
)

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

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_dissmble_demo/data.dart';
import 'package:flutter_dissmble_demo/dissimble_layout_card.dart';
import 'package:flutter_dissmble_demo/model/shopping_item.dart';

class DissmbleDemo extends StatefulWidget {
@override
_DissmbleDemoState createState() => _DissmbleDemoState();
}

class _DissmbleDemoState extends State<DissmbleDemo> {
final List<Dissimble_Item_Model> data = Data.getShoppingItem();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(
'Dismissible',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
letterSpacing: 0.4,
color: Colors.black),
),
centerTitle: true,
),
body: Container(
child: data.length > 0
? ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
return Dismissible(
onDismissed: (DismissDirection direction) {
setState(() {
data.removeAt(index);
});
},
secondaryBackground: Container(
child: Center(
child: Text(
'Delete',
style: TextStyle(color: Colors.white),
),
),
color: Colors.red,
),
background: Container(),
child: DissmbleLayoutCard(movie: data[index]),
key: UniqueKey(),
direction: DismissDirection.endToStart,
);
},
)
: Center(child: Text('No Items')),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information in Trying up the Dismissble widget in your flutter project. We will show you the Dismissble widget is?, and working on it in your flutter applications, So please try it.

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

Clap 👏 If this article helps you.

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.

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.

Quick Action in Flutter

Hello all, I welcome you all to my new blog on Quick action in flutter. This feature is not the most frequently used feature but when the routing of our app becomes bigger then this feature will really help our user to navigate to a particular screen directly.

Although this feature is less demanded by the users but sometimes our clients might ask for it. So let’s get started and learn how to implement it.

Package used:

quick_actions | Flutter Package
This Flutter plugin allows you to manage and interact with the application’s home screen quick actions. Quick actions…pub.dev


Editing pubspec.yaml file:

Install the following dependency in your pubspec.yaml file.

dependencies:
flutter:
sdk: flutter


# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.0
quick_actions: ^0.4.0+10

Understanding quick_actions package:

Before diving into the coding part let’s understand the methods provided by this package.

initialize

This method initializes this package. This method called first and before further interaction.

setShortcutItems

This method takes a list of ShortcutItem that become the quick action.

clearShortcutItems

It removes all the ShortcutItem from the quick action item list.

Let’s code:

Create an object of QuickActions:

QuickActions quickActions = QuickActions();

Initialize the quickActions object inside the initState method:

void initState() {
super.initState();
quickActions.initialize((String shortcutType) {
});
}

Initialize the setShortcutItems :

void initState() {
super.initState();
quickActions.initialize((String shortcutType) {
});

quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'second page',
localizedTitle: 'New Page',
),
]);
}

ShortcutItem is a class inside the quick_actions package that builds a quick action item. It takes a type, localizedTitle, icon parameter. type is a parameter that is passed to the initialize method when the ShortcutItem is clicked. The localizedTitle is the title of ShortcutItem that is display on the long press of the app icon.

Navigating to a new page on taping ShortcutItem :

quickActions.initialize((String shortcutType) {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => SecondPage(
title: shortcutType,
)));
});

We just need to pass the push method inside the initialize method that will navigate to SecondPage.

SecondPage widget:

class SecondPage extends StatelessWidget {
final String title;

SecondPage({this.title});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(title),
),
);
}
}

Let’s create a multiple items list and handling each screen by tapping items:

Adding items to ShortcutItem list:

quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'cart_page',
localizedTitle: 'Cart Page',
),
ShortcutItem(
type: 'order_page',
localizedTitle: 'Order Page',
),
ShortcutItem(
type: 'notification_page',
localizedTitle: 'Notification Page',
),
ShortcutItem(
type: 'place_order',
localizedTitle: 'Place Order',
),
]);

Create four different class for each ShortcutItem:

class CartPage extends StatelessWidget {
final String title;

CartPage({this.title});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(title),
),
);
}
}

class OrderPage extends StatelessWidget {
final String title;

OrderPage({this.title});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(title),
),
);
}
}

class PlaceOrder extends StatelessWidget {
final String title;

PlaceOrder({this.title});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(title),
),
);
}
}

class NotificationPage extends StatelessWidget {
final String title;

NotificationPage({this.title});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(title),
),
);
}
}

To handle all the gestures we will use a switch case that will check for the shortcutType and navigate it to the given page.

quickActions.initialize((String shortcutType) {
switch (shortcutType) {
case 'cart_page':
return _navigate(CartPage(
title: shortcutType,
));
case 'order_page':
return _navigate(OrderPage(
title: shortcutType,
));
case 'notification_page':
return _navigate(NotificationPage(
title: shortcutType,
));
case 'place_order':
return _navigate(PlaceOrder(
title: shortcutType,
));
default:
return MaterialPageRoute(builder: (_) {
return Scaffold(
body: Center(
child: Text('No Page defined for $shortcutType'),
),
);
});
}
});

Navigation method:

_navigate(Widget screen) {
Navigator.of(context).push(MaterialPageRoute(builder: (_) => screen));
}

Demo module:

Full code file:

https://gist.github.com/anmolseth06/db5d91c5990fa43a7b40d6cc66f59f81#file-main-dart


Thanks for reading this article ❤

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

Clap 👏 If this article helps you.

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

Integration Testing With Flutter

0

Brief Introduction

The individual pieces work together as a whole or capture the performance of an application running on a real device. These tasks are performed with integration tests.

Integration testing ( GUI testing) is automated, to avoid having humans do that kind of repetitive work because, frankly, we’re not that great at it. Integration testing attempts to simulate a user interacting with your app by doing things like pushing buttons, selecting items, and typing on the keyboard.


Problems with Flutter_driver

  1. First, issue is that having a separate process for your tests makes it difficult to check the state of your app.
  2. Second, issue is that tests run from the development machine and communicate with the app on the device, which means that the tests aren’t suitable for running on a device farm like Firebase Test Lab.

In this blog, we will learn how to test the authentication flow of ToDo app. I already wrote ToDo app for you so we sharply focus on integration testing.

Follow the steps with me

  1. First, add a dependency in pubspec.yaml under dev
dev_dependencies:
         flutter_test:
           sdk: flutter
         test: ^latest version
         integration_test: ^latest version

2. Your package should have a structure that looks like this:

3.Add this piece of code in test/test_driver/integration_test.dart

import 'package:integration_test/integration_test_driver.dart';

Future<void> main() => integrationDriver();

integrationDriver() : Adaptor to run an integration test using `flutter drive`.

4. Add key as we set in flutter_driver

TextFormField(
key: Key("signInEmailField"),
decoration: textInputDecoration.copyWith(hintText: 'email'),
validator: (val) => val.isEmpty ? 'Enter an email' : null,
onChanged: (val) {
setState(() => email = val);
},
),

Add keys at the widgets which are going to use in the test( our Login flow). You can set according to your test. We are going to test the login flow so we added keys to all field, button etc. I will drop a link for a repository down below you can get a reference through it.

5. Now actual test write under integration_test/foo_test.dart example

For Login Flow.

code sample:

void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();

testWidgets("Sign in test example", (WidgetTester tester) async {

/*
* Setups the finder*/
final Finder signInEmailField = find.byKey(Key('signInEmailField'));
final Finder signInPasswordField = find.byKey(Key('signInPasswordField'));
final Finder signInSaveButton = find.byKey(Key('signInSaveButton'));

await tester.pumpWidget(MyApp());

/*
* pump and settle is same like waitfor in flutter_driver
* */
await tester.pumpAndSettle();

await tester.tap(find.byKey(Key('signInEmailField')));
await tester.enterText(signInEmailField, "test@gmail.com");

await tester.tap(signInPasswordField);
await tester.enterText(signInPasswordField, "123456");

await tester.tap(signInSaveButton);
print("button tapped");

await tester.pumpAndSettle(Duration(seconds: 1));

expect(
find.byWidgetPredicate((widget) =>
widget is AppBar &&
widget.title is Text &&
(widget.title as Text).data.startsWith("ToDoApp")),
findsOneWidget);

await tester.pumpAndSettle(Duration(seconds: 1));
});
}

code sample for check validation:

testWidgets("validate test drive ", (WidgetTester tester) async {


final Finder signInEmailField = find.byKey(Key('signInEmailField'));
final Finder signInSaveButton = find.byKey(Key('signInSaveButton'));

await tester.pumpWidget(MyApp());


await tester.pumpAndSettle();

await tester.enterText(signInEmailField, "");

await tester.tap(signInSaveButton);

await tester.pumpAndSettle(Duration(seconds: 1));

expect(
find.byWidgetPredicate((widget) =>
widget is Text &&
widget.data.contains("Enter an email") ),
findsOneWidget);

await tester.pumpAndSettle(Duration(seconds: 1));
});

6. Foo last run the command in your terminal

flutter drive \
--driver=test_driver/integration_test.dart \
--target=integration_test/foo_test.dart

After running the test :

Happy Fluttering..

Link for repository:

flutter-devs/integration_testing
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!

Expanded and Flexible In Flutter

0

The flutter widget is built using a modern framework. It is like a reaction. In this, we start with the widget to create any application. Each component in the screen is a widget. The widget describes what his outlook should be given his present configuration and condition. Widget shows were similar to its idea and current setup and state. Flutter is a free and open-source tool to develop mobile, desktop, web applications with a single code base.

In this blog, we will explore the Expanded and Flexible Widget In FLutter. We will also implement a demo of the Expanded and Flexible Widget, and describes his properties. and how to use them in your flutter applications. So let’s get started.


Table of Contents :

Flutter

Expanded Widget

Flexible 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 codebase in record time It means that you can use one programming language and one codebase to create two different apps (for iOS and Android).”.

Expanded Widget:

The Expanded Widget is a single child widget. This means that it can have only one child assigned to it. To make this widget work properly, it must be used inside a row or column. And if we equate our child to the widget if we do not want to give the space. We can distribute to that location. We will use flex to distribute this space.

Properties of Expanded Widget:

  • child: Child widget is used to place inside the expanded widget.Which we can take in rows and columns.
  • Flex: The flex property, which uses flex to distributes the available space unevenly between child widgets.

To understand it better, see the code below.

Expanded(
flex: 1,// default
child: Container(),// required field
),

Flexible Widget:

Flexible widgets are basically similar to extends widgets. But there is a slight difference in properties. It is mainly used to adjust different child widgets’ location while having a relationship with their parent widgets.

Properties of Flexible Widget:

  • fit: The fit property controls that. How does the child widget fill the available space?

It has Three options.

1.FlexFit. Tight: Sets it to fill the remaining available space.

2.FlexFit.loose: Sets it to fill the remaining available space. This is as much as the space available to the child widget; let’s grow up.

3.Flex: The flex property, which uses flex to distributes the available space unevenly between child widgets.

To understand it better, see the code below.

Flexible(
flex: 1, // default value
fit: FlexFit.loose, //default value
child: Container(), // required field
),

Demo Module:

In this demo module video.Used Expanded and Flexible Widget, which files the available space according to their own. It has a property called flex that has been used, which can reduce the container’s size.

Code Implement:

Expanded Widget:

As you can see on this screen. There are two rows in this screen that used the Expanded widget in the first row but did not use the flex property inside the Expanded widget.

Let us understand this with the help of a reference.

Row(
children: [
Expanded(
child: Container(
// padding:EdgeInsets.all(10),
alignment: Alignment.center,
color: Colors.pink[300],
height: 100,
child: Image.asset('assets/images/pluginIcon.png'),
),
),
Expanded(
child: Container(
alignment: Alignment.center,
height: 100,
color: Colors.green,
child: Image.asset('assets/images/pluginIcon.png'),
),
),
Expanded(
child: Container(
alignment: Alignment.center,
height: 100,
color: Colors.amber,
child: Image.asset('assets/images/pluginIcon.png'),
),
),
],
),

The Expanded widget results can be seen in the below image.

Flexible Widget:

As you can see on this screen, two containers have been used in this first row, which is wrapped with the flexible widget. And has used properties flex and fit.

Row(
children: <Widget>[
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Container(
height: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.green,
),
),
),
SizedBox(
width: 20,
),
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Container(
height: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.green,
)
),
),
],
),

The Flexible widget results can be seen in the below image.

Code File:

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

class ExpandedWidget extends StatefulWidget {
  @override
  _ExpandedWidgetState createState() => _ExpandedWidgetState();
}

class _ExpandedWidgetState extends State<ExpandedWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Expanded Widget'),
      ),
      body: Container(
        padding: EdgeInsets.all(15),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Expanded widget without flex',
                  style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w500,
                      fontStyle: FontStyle.italic,
                      letterSpacing: 0.5),
                ),
                SizedBox(
                  height: 40,
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        // padding:EdgeInsets.all(10),
                        alignment: Alignment.center,
                        color: Colors.pink[300],
                        height: 100,
                    child:Image.asset('assets/images/pluginIcon.png'
                       ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        alignment: Alignment.center,
                        height: 100,
                        color: Colors.green,
                    child:Image.asset('assets/images/pluginIcon.png'
                       ),
                      ),
                    ),
                     Expanded(
                      child: Container(
                        alignment: Alignment.center,
                        height: 100,
                        color: Colors.amber,
                    child:Image.asset('assets/images/pluginIcon.png'
                       ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Expanded widget with flex',
                  style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w500,
                      fontStyle: FontStyle.italic,
                      letterSpacing: 0.5),
                ),
                SizedBox(
                  height: 40,
                ),
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                        child: Container(
                        alignment: Alignment.center,
                        height: 100,
                        color: Colors.pink[300],
                    child:Image.asset('assets/images/pluginIcon.png'
                       ),
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: Container(
                        alignment: Alignment.center,
                        height: 100,
                        color: Colors.green,
                          child:Image.asset('assets/images/pluginIcon.png'),
                      ),
                    ),
                    Expanded(
                      flex: 3,
                      child: Container(
                        alignment: Alignment.center,
                        height: 100,
                        color: Colors.amber,
                        child:Image.asset('assets/images/pluginIcon.png'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Conclusion:

In this article, I have explained an Expanded and Flexible widget demo, which you can modify and experiment with according to your own. This little introduction was from the Expanded and Flexible widget from our side.

I hope this blog will provide you with sufficient information in Trying up the Expanded and Flexible widget in your flutter project. We will show you the Expanded and Flexible widget is?, and working on it in your flutter applications, So please try it.

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

Clap 👏 If this article helps you.

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

❤ ❤ Thanks for reading this article ❤❤


From Our Parent Company Aeologic

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

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on 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.