Google search engine
Home Blog Page 44

Phone Authentication in Flutter

0

Things that you may likely learn from the Blog ::

YOU WILL LEARN HOW TO

  • CONNECT YOUR FLUTTER APP WITH FIREBASE
  • GET THE SHA-1 KEY USING GRADLE METHOD
  • ENABLE PHONE AUTHENTICATION
  • IMPLEMENT THE PHONE AUTHENTICATION FUNCTIONALITY
  • CONTROL UI ACCORDING TO THE AUTH STATE

Demo module::


Importance of phone authentication::

— Images sound more than words —

Introduction

Authenticating the user identity using the users mobile phone number is referred to as Phone Authentication. This verification method is very secure. because when we enter our phone number the phone number is verified in the first step and if the phone number is correct or exists then only the OTP is sent to the respective mobile, after the verification of the OTP only the users are allowed to access the app data.


Table of content

  1. Installing dependencies
  2. Connecting app with firebase & Enabling phone auth
  3. Verifying phone number
  4. Signing in using OTP
  5. SignOut
  6. Managing the UI using the auth state
  7. GitHub Link

Installing Dependencies::

firebase_auth | Flutter Package
A Flutter plugin to use the Firebase Authentication API. For Flutter plugins for other Firebase products, see…pub.dev

Edit your pubspec.yaml

dependencies:
firebase_auth:

Connecting app with firebase & Enabling phone auth::

Please refer to “Setting up the project” section to connect your app with firebase. I have explaned everything in detail.

Using Firebase Firestore in Flutter
Fetching data from cloud firestoremedium.com

GET THE SHA-1 KEY USING GRADLE METHOD

Open Android Studio, go to app-level build.gradle file, click on “Open for editing on Android Studio”, click on Gradle tab, go to

  • android->Tasks->android->singingReport
  • You will get the SHA-1 key in the run Tab.
  • Note: Use this key while adding an app with firebase in the “Register app” section.

Enabling phone auth

  • Go to the Authentication section, go to the phone sign-in Provider, and enable it.
  • You can also add a dummy phone number and OTP for testing purposes.

Verifying phone number::

Firebase auth provides us verifyPhoneNumber() to verify the phone number. FirebaseAuth.instance will create a firebase auth instance that will allow us to access various methods. This method takes six properties phoneNumber, timeout, verificationCompleted, verificationFailed, codeSent, codeAutoRetrievalTimeout .

String phoneNumber, verificationId;
String otp, authStatus = "";

Future<void> verifyPhoneNumber(BuildContext context) async {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 15),
verificationCompleted: (AuthCredential authCredential) {
setState(() {
authStatus = "Your account is successfully verified";
});
},
verificationFailed: (AuthException authException) {
setState(() {
authStatus = "Authentication failed";
});
},
codeSent: (String verId, [int forceCodeResent]) {
verificationId = verId;
setState(() {
authStatus = "OTP has been successfully send";
});
otpDialogBox(context).then((value) {});
},
codeAutoRetrievalTimeout: (String verId) {
verificationId = verId;
setState(() {
authStatus = "TIMEOUT";
});
},
);
}

We are also displaying the authStautus if the OTP has been successfully sent it will show OTP has been successfully send , if verification Failed then it will show Authentication failed , if your account verification Completed then Your account is successfully verified will be displayed.

Signing in using OTP::

signIn method

We are using a non-Dismissible AltertDialog Box to enter the OTP. After the OTP is entered the OTP will we used as smsCode in the sign-in process.

Future<void> signIn(String otp) async {
await FirebaseAuth.instance
.signInWithCredential(PhoneAuthProvider.getCredential(
verificationId: verificationId,
smsCode: otp,
));
}

verificationId is the id that we receive while verifying the phone number.

Dialog Box

otpDialogBox(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text('Enter your OTP'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration: InputDecoration(
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(30),
),
),
),
onChanged: (value) {
otp = value;
},
),
),
contentPadding: EdgeInsets.all(10.0),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
signIn(otp);
},
child: Text(
'Submit',
),
),
],
);
});
}

SignOut::

FirebaseAuth.instance provides us signOut() method to signOut the current user.

Future<void> _logout() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e.toString());
}
}

HomePage.dart

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

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
Future<void> _logout() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e.toString());
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Phone Auth Demo"),
backgroundColor: Colors.cyan,
),
body: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (context, snapshot) {
FirebaseUser firebaseUser = snapshot.data;
return snapshot.hasData
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"SignIn Success 😊",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
SizedBox(
height: 20,
),
Text("UserId: ${firebaseUser.uid}"),
SizedBox(
height: 20,
),
Text(
"Registered Phone Number: ${firebaseUser.phoneNumber}"),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: _logout,
child: Text(
"LogOut",
style: TextStyle(color: Colors.white),
),
color: Colors.cyan,
)
],
),
)
: CircularProgressIndicator();
},
),
);
}
}

LoginPage.dart

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

import 'dart:async';

class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
String phoneNumber, verificationId;
String otp, authStatus = "";

Future<void> verifyPhoneNumber(BuildContext context) async {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 15),
verificationCompleted: (AuthCredential authCredential) {
setState(() {
authStatus = "Your account is successfully verified";
});
},
verificationFailed: (AuthException authException) {
setState(() {
authStatus = "Authentication failed";
});
},
codeSent: (String verId, [int forceCodeResent]) {
verificationId = verId;
setState(() {
authStatus = "OTP has been successfully send";
});
otpDialogBox(context).then((value) {});
},
codeAutoRetrievalTimeout: (String verId) {
verificationId = verId;
setState(() {
authStatus = "TIMEOUT";
});
},
);
}

otpDialogBox(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text('Enter your OTP'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration: InputDecoration(
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(30),
),
),
),
onChanged: (value) {
otp = value;
},
),
),
contentPadding: EdgeInsets.all(10.0),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
signIn(otp);
},
child: Text(
'Submit',
),
),
],
);
});
}

Future<void> signIn(String otp) async {
await FirebaseAuth.instance
.signInWithCredential(PhoneAuthProvider.getCredential(
verificationId: verificationId,
smsCode: otp,
));
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
),
Text(
"Phone Auth demo📱",
style: TextStyle(
color: Colors.cyan,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
Image.network(
"https://avatars1.githubusercontent.com/u/41328571?s=280&v=4",
height: 150,
),
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
keyboardType: TextInputType.phone,
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(30),
),
),
filled: true,
prefixIcon: Icon(
Icons.phone_iphone,
color: Colors.cyan,
),
hintStyle: new TextStyle(color: Colors.grey[800]),
hintText: "Enter Your Phone Number...",
fillColor: Colors.white70),
onChanged: (value) {
phoneNumber = value;
},
),
),
SizedBox(
height: 10.0,
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
onPressed: () =>
phoneNumber == null ? null : verifyPhoneNumber(context),
child: Text(
"Generate OTP",
style: TextStyle(color: Colors.white),
),
elevation: 7.0,
color: Colors.cyan,
),
SizedBox(
height: 20,
),
Text("Need Help?"),
SizedBox(
height: 20,
),
Text(
"Please enter the phone number followed by country code",
style: TextStyle(color: Colors.green),
),
SizedBox(
height: 20,
),
Text(
authStatus == "" ? "" : authStatus,
style: TextStyle(
color: authStatus.contains("fail") ||
authStatus.contains("TIMEOUT")
? Colors.red
: Colors.green),
)
],
),
),
);
}
}

Managing the UI using the auth state::

FirebaseAuth.instance.onAuthStateChanged provides us the stream of authState. To manage the UI according to the auth state we can use StreamBuilder .

main.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:phone_auth_example/homePage.dart';
import 'signUpPage.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (ctx, userSnapshot) {
if (userSnapshot.hasData) {
return HomePage();
} else if (userSnapshot.hasError) {
return CircularProgressIndicator();
}
return LoginPage();
},
));
}
}

GitHub Link::

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


Who is this course for?

Want to build Flutter apps with native functionalities?

  1. Want to learn advanced Flutter functionality?
  2. Want to learn job-oriented and high-demand, high-paying flutter iOS and android functionality?

What does this course offer?

  1. Flutter Razorpay payment gateway integration: In this module, we shall learn about Razorpay payment gateway integration which will help us to process the payment of the purchases made by the user.
  2. Flutter Stripe payment gateway integration: In this module, we shall learn about Stripe payment gateway integration which will help us to process the payment of the purchases made by the user.
  3. FLUTTER SCAN AND GENERATE QR CODE: In this module, we shall learn how we can scan a QR code and generate the QR code in Flutter.
  4. FLUTTER FIREBASE EMAIL PASSWORD AUTHENTICATION: In this module, we will learn how we can perform authentication using an email password provider, we will also learn how we can verify the user’s email and reset the password.
  5. FLUTTER FIREBASE PHONE AUTHENTICATION: In this module, we will learn how we can perform authentication using a phone authentication provider, and we will see how we can send the OTP to the provided phone number and sign in using the phone credentials.
  6. FLUTTER FIREBASE GOOGLE AUTHENTICATION: In this module, we will learn how to perform authentication using the google authentication provider using firebase in flutter.

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

Thank you for reading. 🌸

Tracking Screen Transition By Route Observer Flutter

0

In this article, We are going to discuss how to observe screen transition in Flutter. As you know Flutter’s widgets do not have any handler methods to handle events related to screen-transitions because widgets do know if they are a part of the screen or whole.

As you know in the flutter navigation is handled by Navigator and is also responsible for screen transitions. There are different options like push, pop screens, and the list of NavigatorObserver can also be passed to Navigator to receive events related to screen-transitions.

A custom NavigatorObserver can also be used but if the handling of it in the state is required then it is a better option to go with the RouteObserver.

What is RouteObserver ?

RouteObeserver is a Navigator observer that notifies RouteAwares of changes to the state of their Route.

A quote from a RouteObserver class to make Its Intention clear.

RouteObserver informs subscribers whenever a route of type R is pushed on top of their own route of type R or popped from it. This is for example useful to keep track of page transitions, e.g. a RouteObserver<PageRoute> will inform subscribed RouteAwares whenever the user navigates away from the current page route to another page route.

Its implementation is quite simple and handy also works very well but when it comes to such an application with various screens it becomes quite huge.

Now let’s understand its working where we would learn its functioning and also get to know how to set different screen transitions in the app as a bonus.

There are two ways to do this as in flutter there are two classes RouteAware and RouteObserver. At first, we would go with RouteAware class.

RouteAware

So lets first understand how does this work and functionalities it possess :

https://gist.github.com/shivanchalaeologic/cf732cc93dd98046c431e928c0bf135b#file-route_aware-dart

As you can understand by reading the above code snippet it is an interface of an object that notifies the current route during transitions and consists of four methods didPopNext(), didPush(),didPop() and didPushNext() these are called at different scenarios as you can read in the code.

Now let’s add this into our code. For this first, we create an instance of RouteObserver then mention all pages where we want to navigate and in navigatorObservers we provide that instance of RouteObserver

https://gist.github.com/shivanchalaeologic/fdf3dd6a084dbc4727343f35792effff#file-main-dart

After that, we move to that RouteAware class from where we will get to know about all the page transitions which are going to take place by using RouteAware() Widget. and get this kind of info :

But for this result like this, we need to implement those four methods mentioned in route_aware.dart. You can implement these methods in every class like this :

https://gist.github.com/shivanchalaeologic/a4ae57023337415312eebc6f79988de3#file-page_two-dart

But writing this boilerplate in every file is not good, So we will make a separate class for this and you will get that expected result.

https://gist.github.com/shivanchalaeologic/c6dce39ba4eb8a46ca819806e113fdd6#file-route_aware-dart

RouteObserver :

RouteObserver is a class that informs user or subscriber if a user navigates to another screen or a route of type “R” is pressed as you can understand easily by reading comments in this official code snippet.

https://gist.github.com/shivanchalaeologic/447fd6290fbb9d4e3d7970853c6cf4ff#file-route_observer-dart

Let’s understand how to use RouteObserver in our app,

The only thing you need to do is by extending RouteObserver you can use those four methods according to your need mentioned in route_aware.dart class.

https://gist.github.com/shivanchalaeologic/3ded41042244c9b1c714863a9b8d3367#file-rout_observer_example-dart

After that, You need to call this class in main.dart & It will automatically notify all the screen transitions.

https://gist.github.com/shivanchalaeologic/24ed18f08f0f14fffbcfaedbd432ef97#file-main-dart

Conclusion

When you are making large scale projects it is necessary to observe transitions meticulously to rectify code compile time its responsiveness then it becomes must because as a developer you get to know about how your app is responding in different scenarios. So as a solution these two techniques are available here to help you out.


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

Dart Extensions Methods

0

As you all know dart is client optimized programming language for multiple platforms and that special term client optimized always indicates that Dart will always come with more suitable and optimized techniques to make developers work with ease. the same thing happened during the announcement of Dart 2.6 when extensions were introduced however that was for a preview but it was finally released in 2.7. Basically extensions feature is the way to add functionality to existing libraries.

If we understand extension methods by a scenario then it would be like

When you’re using someone else’s API or when you implement a library that’s widely used, it’s often impractical or impossible to change the API. But you might still want to add some functionality.

then the most probable solution for that is by writing wrapper classes with static methods and members and it could cause an increase of the number of objects and then extensions feature come in to play.

Sometimes you might get confused in order to clarify the difference between wrapper and extensions so for your information

In Wrapper classes object is passed explicitly to the static methods while in extensions it is extended implicitly.

So this was basic introduction now let’s clarify a few things about extensions

  • How can we use extensions
  • where it is suitable to use and where we should refrain from it

Implementation

Before going over implementation of the extension the first thing which you need to pay attention to is the Dart SDK version. This should be ≥ 3.3, inside your pubspec.yaml

environment:sdk: ">=3.3.0 <4.0.0"

The syntax for the actual implementation

extension <extension_name> on <type> {
(<member_definition>)*
}

Example

Let’s understand it by example, suppose if you are getting data from any third-party API and you are getting value in Celsius but need to show it in Farhenheit, what would you do ??

Simple you would convert it like this

Extension Methods

void main() {

double tempCelsius = 20.0;
double tempFarhenheit = tempCelsius* 1.8 + 32;
// celsiusToFarhenheit();
print('${tempCelsius}C = ${tempFarhenheit}F');

}

but what if you need show throughout in your application then you can do this everywhere but there would be a lot of boilerplate code so here extensions come in because you don’t need to call extensions methods by its name

and the implementation will be like

void main() {

double tempCelsius = 20.0;
double tempFarhenheit = tempCelsius.celsiusToFarhenheit();
print('${tempCelsius}C = ${tempFarhenheit}F');

}
extension on double {
double celsiusToFarhenheit() => this * 1.8 + 32;
}

In this example, we have understood three things

  • It leverages the type system
  • makes our code much easier to understand
  • avoids overloading generic numeric types such as double, with domain-specific logic for temperature conversion.

Extension Operators

void main() {

List prices = [2, 5, 6.75];

print("\nPrice listing after doubling the value");

print(prices ^ 2);
}

extension<T> on List<T> {

List<num> operator ^(int n) =>
this.map((item) => num.parse("${item}") * n).toList();

}

In this example, you can see how we are doubling the values of the list by using extension methods and the output will be

Price listing after doubling the value [4, 10, 13.5]

That was Dart portion, now let’s understand with Flutter

Suppose you are designing UI of app and there are numerous circular Cards where you need to define its shape everywhere so you need to call that circular property everywhere then again we would write the extension method for this see in the example

import 'package:flutter/material.dart';
import 'package:flutter_route_obser/extension_method.dart';

class PageOne extends StatefulWidget {
@override
_PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Card(
color: Colors.green,
shape: ShapeBorderX.roundedRectangle(50),
child: Container(
height: 50,
width: 50,
),
),
),
);
}
}

for the extension methods, we make a separate class where all different extensions are described and we only need to call them.in this example, you can see that we are calling shape from the extension method

import 'package:flutter/material.dart';

extension ShapeBorderX on ShapeBorder {
static ShapeBorder roundedRectangle(double radius) {
return RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(radius),
),
);
}
}

extension WidgetPaddingX on Widget {
Widget paddingAll(double padding) => Padding(
padding: EdgeInsets.all(padding),
child: this,
);
}

extension methods are defined by using extension keyword after that we will be able to call all methods without creating any instance variables.

Conclusion

In conclusion, we found that as a developer we have also options to get rid off of a lot of boilerplate and it helps to use the property of any method without creating any instance variables which a big boon when it comes to using any method from different classes.


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

What is Agile Methodology in Mobile App Development

0

Agile Methodology is one of the most commonly used practices in project management in current times. The benefits that the method provides such as increased business value, faster go to market, greater transparency among the team, and better quality management is enough to push a number of businesses across a range of industries to follow the Agile approach in their everyday work process.

If your business, seeing the benefits that the methodology has to offer, is also planning to take the agile scrum development route, this article is for you.

Agile Method In the context of Mobile App Development

Holistically, the role of Agile in mobile apps is well-renowned and Scrum is the most commonly used subdomain of the agile methodology, which has quickly expanded to handling big, complicated projects that might have otherwise taken a lot of time to finish.

Mobile application development and keeping it updated in the current scenario is quite a complex process. Even more complex is the task of getting it downloaded on the user’s devices, and used frequently. It is because of a large number of apps available in the marketplace. While a majority of users use the smartphone, it is quite easy to get noticed, but it becomes quite challenging to get the user’s attention as in this gigantic sea of options available for them. Hence it becomes quite necessary for the business owners to design the best app in a short span of time and keep their apps updated as per the latest trends.

Before getting into the details about the Agile methodology of mobile app development, it is necessary to have a brief idea of Agile technology.

What Exactly is Agile?

Agile is an iterative and step-by-step software development methodology. Agile application development helps organize designing and planning methods, development, and testing methods during a software lifecycle. All methods of Agile are based on the following principles:

  • quick response to any changes with the help of adaptive planning.
  • joint elaboration of requirements.
  • rationalization of tasks performed by the development team
  • step-by-step software development with strict time frames.

How Does Agile Work?

Since the Agile app development methodology consists of a few short cycles (2–3 weeks each), there is risk minimization. A customer can see the result after each cycle, and he/she can request to make any changes. Thus, a customer has a direct influence on the development and he/she controls it. Each Agile application development lifecycle includes the following stages:

  • Requirement analysis
  • Design
  • Development
  • Testing
  • Deploy
  • Review

One cycle isn’t enough for building a full-fledged product, but each iteration shows part of the functionality that can be tested and/or changed. After each cycle, the development team sums everything up and can receive new requirements, then some adjustments can be made in the software development plan.

Why is Agile Methodology Good For Mobile App Development?

Now let’s speak about the application of Agile in mobile app development and why use Agile methodology. What particularities do mobile apps have? Unlike conventional desktop applications for PC that may function for a few years without an upgrade, mobile apps should be much more flexible for users. Users’ demands may change rather often, so app owners should update this app every time when it requires new changes. And what is the way to create a high-quality mobile app without additional revisions? Agile methodology is the option.

In-Depth Planning in Real-Time Mode

It can be rather difficult to prepare a plan for the whole development process. Using Agile methodology for mobile application app development, we can prepare a plan for each cycle separately, we don’t waste extra time and resources to fix any bugs since everything can be fixed after each stage of implemented functionality. So we can make a proper plan for each stage without any problems, and it will help us create a first-rate product. By the way, if you should also know how to arrange budget planning for your software project.

Sprint by Sprint

With the help of Agile, we create the software sprint by sprint, as we indicated before. We call each cycle as sprint since it is similar to run on a short distance. We don’t aim to complete the project as quickly as possible, we test and check functionality after each sprint to see whether it works properly or not. Besides that, with Agile we can keep up with more strict deadlines.

Quick Changes

Due to the Agile methodology in mobile application development, it is very convenient to make changes in the app since it is divided into sprints. Thus, it will not have a negative impact on the development process, and changes can be made quickly. Because when the project is almost finished and some serious problems arise, revision can take much more time and money, so Agile methodology helps avoid such situations.

Efficient Risk Management

Users won’t use an app that doesn’t function properly or it has many bugs. It will lead to a total failure of the app. That is why an app can be released step by step with Agile methodology, in the beta version first, to make it possible for users to assess an app and notify about any bugs if they find it. On the basis of it, developers can make all changes quickly, and all risks can be managed timely. Existing bugs will be detected as early as possible. You can see how we organize risk management when we create your app.

Complete Transparency

It is not an acceptable situation when a customer sees a result of the development in the end. If something doesn’t meet expectations of a customer, it will be more difficult to revise the app, it will lead to additional costs and time, and, as a result, to negative feedback from a customer. Agile methodology allows the development team to be always in touch with a customer, provide him/her with an app when each sprint is completed, and if we need to make any changes — we do it quickly without damaging development processes.

So, you can see the main benefits Agile mobile app development methodology brings for mobile app development. Now, let’s move to the most popular framework of Agile.

Benefits of Agile Over Traditional Project management Method

Many developers and project managers prefer to use the agile methodology for a variety of reasons. Some of them are discussed below:

More flexibility

When it comes to making changes in the product or a process, agile methodology is much more flexible than the waterfall methodology. While working, if team members feel that there is a need to experiment and try something different than as planned, the agile methodology easily allows them to do so. The best thing about this methodology is that it focuses more on the product than following a rigid structure.

Unlike the traditional approach, agile methodology isn’t linear or follows a top-down approach. So, any last-minute changes can be accommodated in the process without affecting the end-result and disrupting the project schedule.

Transparency

In agile methodology, everything is out there and transparent. The clients and decision-makers are actively involved in the initiation, planning, review, and testing part of a product. Whereas in the traditional approach, the project manager is holding reins of the project, thus others don’t get to make the major decisions.

Ownership and accountability

In traditional project management, a project manager is the person of the ship which means that the entire ownership belongs to him/her. Customers are also involved during the planning phase but their involvement ends there and then as soon as the execution starts.

In the agile methodology, every team member shares ownership of the project. Each one of them plays an active role to complete the sprint within the estimated time. Unlike traditional project management, everyone involved in the project can easily see view the progress from the beginning to an end.

Scope For Feedback

In the traditional approach, every single process is clearly defined and planned from the beginning of the project. The project has to be completed within the estimated time and budget. So, any big change or feedback that might push the deadline is skipped. Whereas agile management allows constant feedback that is helpful in providing better output.

Scrum

Scrum is another prevalent agile methodology process that implements flexible process control for complex software projects. It also makes use of iterative and incremental practices. Based on the hypothesis that we cannot define the final requirements of the project, in the beginning, the knowledge is gained over the due process from the mistakes made over time. It solely focuses on checking the progress of the project and resolve the difficulties as soon as it is encountered in frequent meetings. It provides the advantage that it helps to take action as and when the requirement changes.

Scrum approach divides the working process into equal sprints — their duration may vary, everything depends on the specific project. Before we start a sprint, it is necessary to draw up tasks for this sprint. When it is completed, all results are discussed. This method makes it possible to lower development costs and make the management process more efficient.

Scrum Development: Responsibility Participants

The techniques of Scrum has become very popular and now considered to be the most important thing to do before starting any project. That is why the demand of the scrum masters and other professions related to the scrum has also increased, and people now are searching about the term scrum more.

The scrum is a very specific and précised framework that is why it comprised of the following roles.

  • Scrum Master
  • Product Owner
  • Scrum Team
  • Stakeholders

Scrum Master is someone who is responsible for solving any sort of problem that the team is facing while building the product. It is not necessary for him to completely understand the requirements; he must be capable enough to find solutions to situations. He has to create and maintain the best possible working condition for the team members so that they can meet the goals of each sprint effectively.

Product Owner is the one who shares the vision of the project (or the product to be developed), prioritizes the functionalities to be built and makes key decisions on behalf of the team or the project. While during project execution, the product owner is the one who is responsible for maintaining the product backlog, bridging the gap between the developers and other stakeholders, managing the end-user (or customer) expectations, and managing the budget (ROI). He is also the one who takes a call on the quality of the product and if it requires any improvement.

A Scrum Team is cross-functional team that is responsible for developing the product. It is a small team consisting of developers, business analysts, testers, etc. The team works together and in tandem while building the application. The activities of each of the team members are aligned in a way such that the targets associated with a specific sprint are achieved. Team members are also responsible for identifying the complexity of the tasks (assigned to them) and allocating efforts (in a number of hours/days) to those.

Conclusion

The agile application development process bears a lot of advantages both for the development team and for customers. We can affirm it as we are highly experienced in it. The methodology makes it possible to build a mobile app that will be accepted by the public with admiration. The only thing you need is a high-skilled software development team that will turn your ideas into reality.


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. Team FlutterDevs has been building remarkable mobile apps in Native, Hybrid, and Cross-platform over a decade now. Hire a flutter developer for your 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 Performance Optimization

Ever wondered how flutter handles all your UI building and events like Futures, taps, etc.. on a single thread( yes it does all that on a single thread 😮😮😮 until and unless explicitly done).

What is Thread/Isolates ?

Thread is an independent process that has its own chunk of memory and executes the given instructions on that memory , It can work parallelly with other threads hence can reduce execution time of multiple process on a single thread .

Let’s understand this with an example :

In Fps games like counter strike, Call of duty, etc. you can see that as soon as you fire a weapon few tasks executes simultaneously like playing of bullet sound, change of bullet count and reduction in opponent health , All these things happens parallelly these are basically threads which execute parallelly and execute their task on separate isolates(isolates and threads can be used interchangeably as isolate is a Dart way of multi threading more on that below) which have its own memory.

Languages like JAVA and C++ Share Their heap memory with threads, but in case of flutter, every isolate has its own memory and works independently. As it has its own private space this memory doesn’t require locking, as if a thread finishes its task it already means that the thread has finished utilizing its memory space and then that memory can go for garbage collection.

To maintain these benefits flutter has a separate memory for every isolate(Flutter way of multi-threading) that’s why they are called isolate 🙂.

Learn more about isolates below.

How can it be helpful to me and where should I use isolates/Threads?

When to use isolates/threads ?

There are a few situations where isolates can be very handy.

  1. Let say you want to execute a network call and you want to process that data that you just received . and that data contains about million records that alone will hang your UI.
  2. You have some image processing tasks that you want to do on-device these kinds of tasks are highly computational as they have to deal with lots of number crunching operations which may lead to frozen UI or legginess in UI.

So to conclude when to use isolates, We should use them whenever you think there is a lot of computation that needs to be offloaded from the main thread.

How to use isolates ?

Flutter team has designed a very elegant and abstract way of using isolates/threads in a flutter, Using compute we can do the same task which isolates does but in a more cleaner and abstract way. Let’s take a look at the flutter compute function.

Syntax:

var getData = await compute(function,parameter);

Compute function takes two parameters :

  1. A future or a function but that must be static (as in dart threads does not share memory so they are class level members not object level).
  2. Argument to pass into the function, To send multiple arguments you can pass it as a map(as it only supports single argument).

compute function returns a Future which if you want can store into a variable and can provide it into a future builder.

Let’s start by analyzing a sample problem:

/media/247dce48c8ac87e5b91b48cd11740086

In the above code pausefunction() is called just below the build method which pauses the execution of code for 10 seconds. And because of that when you try to navigate to this page from a previous one there will be a delay of ten seconds before our page gets pushed on to the widget tree.

We can try to resolve this issue by using async.

https://gist.github.com/702x/24a798189ac096e688f8301f0e2381f2#file-with10seconddelay-dart

As you can see now we have declared our pause function as async even doing this will not help

As async in dart is basically puts our code in ideal until there is something to compute so it seems to us that dart is executing these on a different thread but actually it’s just waiting for some event to occur in that async function.

More on async below :

https://gist.github.com/702x/b50dba38b3aae2e592bd26e2a94a1da5#file-with10seconddelayasync-dart

Let’s solve the above issue using compute.

In the above code, we basically passed our function in compute() function and that creates a separate isolate to handle the task and our main UI will still run without any delay (check the debug console for response ).

Summary:

  1. Dart is by default executes all its code on a single-threaded.
  2. Every function and every async-await calls work only on the main thread(until and unless specified).
  3. We can create multiple threads using compute( Future function/normal function, argument).
  4. You can use compute for executing network calls, performing number-crunching calculations, image processing, etc.

This is all about compute to learn more about isolates (the underlying architecture of computing function) check out isolate .

Thanks for reading this article.

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

Check out full code at FlutterDevs GitHub.


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

Twitter Authentication In Flutter

0

Demo module :

Introduction

In this blog, we shall discuss user authentication using firebase in flutter. We will learn authentication using twitter, email, and password, anonymous methods.


Table of content

: Connecting app to firebase

: Installing required package

: Anonymous auth

: Authentication using Email and Password

: Authentication using Twitter


Connecting app to firebase

  1. Open firebase, click on get started which will take you to the Add Project screen.
  2. Enter the project name and complete the other essential steps. It will take you to your project screen, click on the android icon.
  3. Now the steps which are coming are very important so please do them very carefully. You have to enter the package name which is generally your application Id in your app-level build.gradle file. Add the other two optional fields if you wish to add them as well.
  4. Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory. (NOTE: Please check the file that you have downloaded has a google-services.json name or not because if you download it more then one time the name of the file changes to google-services(2).json(for example), so please remove (2) from the file name or rename it to google-services.json)
  5. You will see the following screen.

Here the first block contains the classpath that you have to add into your project level build.gradle file under the dependencies section. The second section contains a plugin and dependencies that you have to add it into your project app-level build.gradle file. Please add these lines properly and carefully if you are adding them for the first time.

Left: project/build.gradle ….Right :project/app/build.gradle

6. Now you should restart your application (NOTE: Please refer full restart not hot reload). Wait for few seconds and your application will be successfully added with firebase. If you see the bellow screen on your firebase then you have successfully added firebase to your app…

Congratulation…

Installing the required package

Update your pubspec.yaml with the following dependency.

flutter_twitter_login | Flutter Package
A Flutter plugin for using the native TwitterKit SDKs on Android and iOS. This plugin uses the new Gradle 4.1 and…pub.dev

firebase_auth | Flutter Package
A Flutter plugin to use the Firebase Authentication API. For Flutter plugins for other Firebase products, see…pub.dev

dependencies:
flutter:
sdk: flutter
firebase_auth: ^latets version
flutter_twitter_login:

Anonymous auth

: Go to the authentication tab in the Firebase console then enable anonymous authentication from the Sign-In Option.

: Sign In Function

Future<void> _signInAnonymously() async {
try {
await FirebaseAuth.instance.signInAnonymously();
} catch (e) {
print(e);
}
}

Try: contains code that may throw an exception.

Catch: used to handle an exception.

This method calls the FirebaseAuth.instance.signInAnonymously() ,return a user.

: Sign Out Function

Future<void> _signOut() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e);
}
}

This method triggers the signOut method to signOut the user.


Authentication using Email and Password

: Setting up the variables

final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;

NOTE: FirebaseAuth is the entry point of the FirebaseAuthenticationSDK.

: Sign In Function

void _signInWithEmailAndPassword() async {
await _auth.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
}

signInWithEmailAndPassword() method sign in a user with the given email address and password.

If sign In successful, it also signs the user in into the app and updates
the
onAuthStateChanged stream.

If sign In is unsuccessful, it shows three types of error:-

  1. ERROR_WEAK_PASSWORD: If the password is not strong enough.
  2. ERROR_INVALID_EMAIL: If the email address is malformed.
  3. ERROR_EMAIL_ALREADY_IN_USE: If the email is already in use by a different account.

: Sign Up Function

_signUpWithEmailAndPassword() async {
await _auth.createUserWithEmailAndPassword(
email: _emailController.text, password: _passwordController.text);
}

createUserWithEmailAndPassword() create a new user account with the given email address and password.

If successful, it also signs the user into the app and updates the onAuthStateChanged stream.

You must enable Email & Password accounts in the Auth section of the Firebase console before being able to use them.

If sign In is unsuccessful, it show error:-

  1. ERROR_INVALID_EMAIL — If the [email] address is malformed.
  2. ERROR_WRONG_PASSWORD — If the [password] is wrong.
  3. ERROR_USER_NOT_FOUND — If there is no user corresponding to the given [email] address, or if the user has been deleted.
  4. ERROR_USER_DISABLED — If the user has been disabled (for example, in the Firebase console)
  5. ERROR_TOO_MANY_REQUESTS — If there were too many attempts to sign in as this user.
  6. ERROR_OPERATION_NOT_ALLOWED — Indicates that Email & Password accounts are not enabled.

: Sign Out Function

_logOut() async {
try {
await _auth.signOut();
Navigator.of(context).pop();
} catch (error) {
print(error);
}
}

signOut() method Signs out the current user and clears it from the disk cache.

If successful, it signs the user out of the app and updates the onAuthStateChanged stream.

: Reset Password Function

_resetPassword() async {
try {
_auth.sendPasswordResetEmail(email: email);
} catch (error) {
print(error);
}
}

sendPasswordResetEmail() method triggers the Firebase Authentication backend to send a password reset email to the given email address, which must correspond to an existing user of your app.

If it is unsuccessful then it gives error:

  1. ERROR_INVALID_EMAIL — If the email address is malformed.
  2. ERROR_USER_NOT_FOUND — If there is no user corresponding to the given email address.

Authentication using Twitter

Setting up the Project

  1. Plugin Used

flutter_twitter | Flutter Package
A Flutter plugin for using the native TwitterKit SDKs on Android and iOS. This plugin uses the new Gradle 4.1 and…pub.dev

2. Go to https://apps.twitter.com/ and make a developer account.

NOTE: Do not forget to add the callback URLs. You need to add three callback URL

  • for android:twittersdk: //,
  • for ios: twitterkit-CONSUMERKEY: //
  • add the URL that you get while enabling the twitter authentication from firebase.

You can add URL only for ios or for android.

3. Enable twitter sign-in option in the firebase console. (Paste the consumerKey, consumerSecret in the API key and API secret section respectively)

3. Click enable

We are now ready to go

: FirebaseAuth instance

Let’s create a firebase auth instance.

FirebaseAuth _auth = FirebaseAuth.instance;

: TwitterLogin

flutter_twitter_login provides us TwitterLogin class that takes consumerKey and consumerSecret that we got during creating the twitter developer account.

final TwitterLogin twitterLogin = new TwitterLogin(
consumerKey: 'YOUR CONSUMERKEY',
consumerSecret: 'YOUR SECRETKEY',
);

: Sign In Function

void _signInWithTwitter(String token, String secret) async {
final AuthCredential credential = TwitterAuthProvider.getCredential(
authToken: token, authTokenSecret: secret);
await _auth.signInWithCredential(credential);
}

: Logging in User

void _login() async {
final TwitterLoginResult result = await twitterLogin.authorize();
String newMessage;
if (result.status == TwitterLoginStatus.loggedIn) {
_signInWithTwitter(result.session.token, result.session.secret);
} else if (result.status == TwitterLoginStatus.cancelledByUser) {
newMessage = 'Login cancelled by user.';
} else {
newMessage = result.errorMessage;
}

setState(() {
message = newMessage;
});
}

: LogOut

void _logout() async {
await twitterLogin.logOut();
await _auth.signOut();
}

: Full code

import 'package:flutter/material.dart';
import 'package:flutter_twitter_login/flutter_twitter_login.dart';
import 'package:firebase_auth/firebase_auth.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (ctx, userSnapshot) {
if (userSnapshot.hasData) {
return LogOut();
} else if (userSnapshot.hasError) {
return CircularProgressIndicator();
}
return SignInScreen();
},
),
);
}
}

class SignInScreen extends StatefulWidget {
@override
_SignInScreenState createState() => _SignInScreenState();
}

class _SignInScreenState extends State<SignInScreen> {
String message;

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.network(
"https://www.3nions.com/wp-content/uploads/2020/01/comp_1.gif",
height: 200,
),
InkWell(
onTap: () {
_login();
},
borderRadius: BorderRadius.circular(30),
splashColor: Colors.blue,
child: Container(
height: 50,
width: 300,
child: Center(
child: Text(
"Sign In using twitter",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.blue,
width: 3,
)),
),
),
SizedBox(
height: 20,
),
Text(
message == null ? "" : message,
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
),
),
InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) {
return EmailPasswordScreen();
},
));
},
borderRadius: BorderRadius.circular(30),
splashColor: Colors.blue,
child: Container(
height: 50,
width: 300,
child: Center(
child: Text(
"Sign In using email and password",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.blue,
width: 3,
)),
),
),
SizedBox(
height: 40,
),
InkWell(
onTap: () {
_signInAnonymously();
},
borderRadius: BorderRadius.circular(30),
splashColor: Colors.blue,
child: Container(
height: 50,
width: 300,
child: Center(
child: Text(
"Sign In as anonymous user",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.blue,
width: 3,
)),
),
),
],
),
),
);
}

void _login() async {
final TwitterLoginResult result = await twitterLogin.authorize();
String newMessage;
if (result.status == TwitterLoginStatus.loggedIn) {
_signInWithTwitter(result.session.token, result.session.secret);
} else if (result.status == TwitterLoginStatus.cancelledByUser) {
newMessage = 'Login cancelled by user.';
} else {
newMessage = result.errorMessage;
}

setState(() {
message = newMessage;
});
}
}

final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
FirebaseAuth _auth = FirebaseAuth.instance;

final TwitterLogin twitterLogin = new TwitterLogin(
consumerKey: '',
consumerSecret: '',
);

void _signInWithTwitter(String token, String secret) async {
final AuthCredential credential = TwitterAuthProvider.getCredential(
authToken: token, authTokenSecret: secret);
await _auth.signInWithCredential(credential);
}

void _signInWithEmailAndPassword() async {
await _auth.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
}

_signUpWithEmailAndPassword() async {
await _auth.createUserWithEmailAndPassword(
email: _emailController.text, password: _passwordController.text);
}

Future<void> _signInAnonymously() async {
try {
await FirebaseAuth.instance.signInAnonymously();
} catch (e) {
print(e);
}
}

_logout() async {
await twitterLogin.logOut();
await _auth.signOut();
}




class LogOut extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Auth Demo"),
),
body: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (context, snapshot) {
FirebaseUser firebaseUser = snapshot.data;
return snapshot.hasData
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"SignIn Success 😊",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
SizedBox(
height: 20,
),
Text("UserId: ${firebaseUser.uid}"),
SizedBox(
height: 20,
),
firebaseUser.photoUrl == null
? SizedBox(
height: 0,
)
: Image.network(
firebaseUser.photoUrl,
height: 100,
),
Text("Your name: ${firebaseUser.displayName}"),
Text("Your email: ${firebaseUser.email}"),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () {
_logout();
},
child: Text(
"LogOut",
style: TextStyle(color: Colors.white),
),
color: Colors.blue,
)
],
),
)
: CircularProgressIndicator();
},
),
);
}
}

class EmailPasswordScreen extends StatefulWidget {
@override
_EmailPasswordScreenState createState() => _EmailPasswordScreenState();
}

class _EmailPasswordScreenState extends State<EmailPasswordScreen> {
bool isSingIn = true;

@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Enter your email password",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 25),
),
Card(
elevation: 5,
child: TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hintText: "Email", prefixIcon: Icon(Icons.email)),
),
),
Card(
elevation: 5,
child: TextField(
controller: _passwordController,
decoration: InputDecoration(
hintText: "Password", prefixIcon: Icon(Icons.lock_outline)),
),
),
RaisedButton(
color: Colors.blue,
onPressed: () {
isSingIn
? _signInWithEmailAndPassword()
: _signUpWithEmailAndPassword();
Navigator.of(context).pop();
},
child: Text(
isSingIn ? "Sign In" : "Sign Up",
style: TextStyle(color: Colors.white),
),
),
FlatButton(
onPressed: () {
setState(() {
isSingIn = !isSingIn;
});
},
child: Text(
isSingIn ? "Create an account" : "Already have an account"))
],
),
),
);
}
}

: GitHub Link

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

: If you want to perform local authentication using fingerprint, you can read the my blog post on Local Authentication in Futter .

Local Authentication in Flutter
Local Authentication in Fluttermedium.com

Google Sign In With Flutter
Google sign-in with Flutter using Firebase authenticationmedium.com

Phone Authentication in Flutter
Building a phone number authentication flutter appmedium.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 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!.

Facebook Login In Flutter

0

Login has become one of the most important parts of lives for a developer by having a working on-boarding system we can help tend to users need better than ever. hence why it has become a necessity in almost all the apps.

Because of This most companies have brought out a way for users to login seamlessly through their own apps companies like Facebook, Google and Twitter have made it so that u can log in in 1 click, and with flutter, It has become even simpler to implement.


What you will need?

A couple of packages from pub.dev, enable Facebook for developers and Twitter for Developers.

Packages are:

flutter_facebook_login: ^latest version
 http: any

What we are going to do?

How to access the required data of user through Facebook

Before we can just start logging in there are a few steps that are required to do for logging in Facebook.

Facebook :

  1. So first of all you will have to enable Facebook for developers that is the only way for you to get access to your app ID and app secret, if you have a Facebook profile then it only takes a minute to do it.
  2. After making an account make an app in Facebook for developers after which you will get access to your app ID and app Secret (to reveal app secret go into settings then basic it should look like this:
All the information required to make the sign In happen is in here

3. Now that we have created Facebook for developer’s profiles and have gotten access to our secret key and app ID we can move over to Firebase project to take the necessary steps for log in.

4. Ok once you are at the firebase project you can go to Authentication and then select sign-in methods.

4. Select the Facebook option, it will ask for your App ID and App secret the one you got from Facebook for developers.

5. This will help you in Signing In with Facebook and after that you need to copy that O’auth http link cause it is very important(save it in a text file)

6. Now you will need to go to https://developers.facebook.com/docs/facebook-login/android, to take other actions that will enable you to Sign In through Facebook(Not much left just 3–4 more steps). Don’t worry we are here for full support and will guide you through them as well.

7. Since we are not working with native android we can actually skip many of those steps(GOD I LOVE HOW EASY FLUTTER MAKES EVERYTHING ELSE), we can start at step 1 and choose our project name(the one we just created in Facebook for developers. So go ahead and select it

Choose your app you want to enable facebook login for

8. After selecting it we can jump directly to step 5, now there you will need to provide your app’s package name and main activity name there you can find them if you go through your app-level module and opening src t find AndroidManifest.xml (the path is android/app/src/main/AndroidManifest.xml)

Enter your package name and main activity in both fields

9. Now we come to the part that took me the longest and was very troublesome (don’t worry I went through the pain so you guys don’t have to!), so we come to Step 6 where now we need to provide release key for this,

so the things you will need to generate a release are(unless you have your app published on Play Store you will get your release key in SHa1 from there but you will have to convert it to base64 which you can do by a simple google search)

A) openssl which u can get at https://code.google.com/archive/p/openssl-for-windows/downloads , after downloading it save it on your C: drive in a seperate folder and name it something like “open ssl”

B) you need to have jdk installed on your system to be able to generate the keys : https://www.oracle.com/java/technologies/javase-jdk13-downloads.html

After that you will need to open command line in jdk folder

(the path is C:\Program Files\Java\jdk1.8.0_261\bin), once opened you need to run this command :

  • keytool -exportcert -alias androiddebugkey -keystore “C:\Users\USERNAME\.android\debug.keystore” | “PATH_TO_OPENSSL_LIBRARY\bin\openssl” sha1 -binary | “PATH_TO_OPENSSL_LIBRARY\bin\openssl” base64

remember to fill in your own details in the command like your username and the path to open SSL (if you followed what I have said completely then it will be : “C:/open SSL/bin/OpenSSL” fill it in both places where it is required.

It will then generate the key required to for logging in to Facebook, it will be of 28 characters minimum and will end with an “=”

the release key should be added there

10. Now we are really close to completing our Facebook login all we need right now is to put our O’auth(remember this guy from step 5?), all you need to do now is go back to your Facebook for developers(the one where you created your app) and then you will see product + icon there click it.

after clicking on product and doing the additional steps you will have facebook login option there

After getting facebook login option there you can click it then select settings and then you will encounter this page:

See the censored part? That’s where you will have to put in your O’auth you got from Firebase(in case you didn’t save it you can go back and click on edit option in Firebase Sign in methods to get it again)

After that save changes.

11. Now we can finally move onto our project and add some configuration there as well

Go to your /android/app/src/main/res/values/ and find if you have a Strings.xml file if you dont have it create one, after creating one you can enter this information in it :

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Your App Name here.</string>

<!-- Replace "000000000000" with your Facebook App ID here. -->
<string name="facebook_app_id">YOUR APP ID HERE</string>

<!--
Replace "000000000000" with your Facebook App ID here.
**NOTE**: The scheme needs to start with `fb` and then your ID.
-->

<string name="fb_login_protocol_scheme">fbYOUR APP ID</string>
</resources>

DO as told in the comments.

Now go over to your <your project root>/android/app/src/main/AndroidManifest.xml and add the following just above the “<! — Don’t delete the meta-data below.” comment in androidManifest.xml file then add the following

<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>

<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />

<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>

After you are done with that part, you are almost good to go(there are some specific IOS configurations which you can find in https://pub.dev/packages/flutter_facebook_login be sure to do them as well if you want it to work for IOS as well)

Now in your project make a HelperClass called Authentication.dart

In the file you need to make a function that will help you sign the user into Facebook :

first of all import all these files

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:flutter_twitter_login/flutter_twitter_login.dart';
import 'package:http/http.dart' as http;

After this make an object of FacebookLogin() and write the following function

final fbLogin = FacebookLogin();

Future signInFB() async {
final FacebookLoginResult result = await fbLogin.logIn(["email"]);
final String token = result.accessToken.token;
final response = await http.get('https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email&access_token=${token}');
final profile = jsonDecode(response.body);
print(profile);

return profile;
}

After that, you can call that function in your button like

RaisedButton(
onPressed: () {
Authenticate auth = Authenticate();
auth.signInFB().whenComplete((onComplete) {Navigator.of(context}.push(MaterialPageRoute(builder: (context)=>HomePage()));
},

Its that simple.

Congratulations you have achieved Facebook login, now on your app after clicking on sign In FB button you will be redirected to Facebook page to allow sign in and after allowing in you can see it print users data which you can store in your database and then log them in.


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.

www.flutterdevs.com

Stateful & Stateless: A Doubt Clearing Session

As a flutter developer, you have at least once come across a question of how would you draw a line between Stateless and Stateful, either this question would have been thrown on you or it has hit your mind hard by self-realization. However, it does not matter from where you get stuck here but the main point is….. Do you have any answer to it ?

Of course in search of this mysterious question, you would find that self-proclaimed complete definition on google which is…

If a widget can change — when a user interacts with it, for example — it’s stateful. A stateless widget never changes. Icon , IconButton , and Text are examples of stateless widgets. … A widget’s state is stored in a State object, separating the widget’s state from its appearance.

But if you have ever been a part of a discussion or have appeared for an interview (like me) then you must be aware that the conversation over stateless and stateful does not end here.

whaaatttt… ???? yes, the conversation does not end here.

After giving this definition a question arrives if the stateless widget has a stateful child what it would be called? Does it become a stateful widget or how it manages itself?

So….In the layout, if we choose there can be different widgets like a container which we will select as a stateless widget and it’s child also a container but we will take as a stateful widget and when you would rebuild then the state will only affect stateful container so it does not matter if the parent widget is stateful or not if the child is a stateful widget.

Actually you can say

The only thing which makes them different is the ability to reload at the run time

But the conversation does not end here

so let’s take another definition to conquer the dilemma

The important thing to note here is at the core both Stateless and Stateful widgets behave the same. They rebuild every frame, the difference is the StatefulWidget has a State object which stores state data across frames and restores it.

If you are in doubt, then always remember this rule: If a widget changes (the user interacts with it, for example) it’s stateful. However, if a child is reacting to change, the containing parent can still be a Stateless widget if the parent doesn’t react to change.

That effort was from my side but a description is not fully completed until we don’t know the view of others so let’s have some thoughts :

In this video, a simple definition of stateful and stateless is given

Stateless is Data less and Stateful is Data full

In this video, things have described in some interesting way so first, you should know what is the state

State The state is the information that can read synchronously when the widget is built and might change during the lifetime of the widget and that state changing requirement defines if the widget is stateful or stateless.

Incidentally, the difference between the stateful and stateless widget is very limited, the stateless widget can only once on to the screen while a stateful widget can be drawn multiple times.

Which effectively means that the build function of the stateless widget can be called only once when the class is instantiated or an object is created while in stateful widget build function can be called multiple time during run time and it also states that the content in stateless is immutable while in stateful it is mutable.

The build(…) function of the StateLessWidget is called only ONCE. To redraw the StatelessWidget, we need to create a new instance of the Widget.

After reading that much of content now must b able to create your own analogy which might help you to create your own way of explaining things completely with ease.

Introduction to widgets
Flutter widgets are built using a modern framework that takes inspiration from React. The central idea is that you…flutter.dev

Summary

So this was the discussion that could help you to find your at the stage where at least you can have an explanation for the question which is generally asked during the conversation or that is asked to check one’s root knowledge.

There might be some aspects which I forgot to explain but as soon as I get to know I would try my fullest to update and as you know that this conversation began from widgets and it should go further to with different topics of flutter or as a series and in the next topic we would come with some new fundamental things.

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

Interactive Viewer In Flutter

0

The Interactivity in Flutter just became 100 times better with the new widget called — Interactive Viewer, released in Flutter version 1.20, It immediately became the one thing everyone fell in love with(yes, including me.)

So, What does the widget do ?

By wrapping up your widgets in Interactive Viewer you can do actions such as drag, drop, zoom etc. with your widgets and not only that but with the introduction of Flutter version 1.20 the drag and drop capabilities have became even more polished.


An example of what this widget is capable of :

zoom and drag just by wrapping the image with one widget

Now, lets talk about how it works:

1. Lets take an image and save it in the assets folder.

2.Now add that image to the pubsepc.yaml file:

assets:
- assets/tiger.jfif

3. after that we can use the image in our app like this

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
String tiger = "assets/tiger.jfif";
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SafeArea(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Center(
child: Image.asset(tiger),
),
),
),
),
);
}
}

4. Now all we need to do is to wrap that image.asset widget with interactiveViewer and we are done :

Tip: use the alt+enter command on android studio, saves a lot of time.

InteractiveViewer(
child: Image.asset(tiger),
),

And now you are done, you can now interact with your image however you Like

Now that we know what the widget does and how to use it, lets explore what it is capable of :

There are certain properties of Ineractive Viewer widget so lets explore them.

Note : before we start exploring some of the properties of this widget it will be better to take a look at the official documentation as well.

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

Now, we can jump straight into it.

  1. maxScale

One of the best and most used properties of this widget would be maxScale, it represents how much you can stretch the image.It takes the value of double in it.

Example :

InteractiveViewer(
child: Image.asset(tiger),
maxScale: 5.0,
),

with this you will be able to stretch it 5 times more than what you were able to before, this property helps us to set how much stretch should be allowed on an image.

2. minScale

This property works opposite to maxScale, however it take a double value as well. It represents how much you can squeeze an image.

Example :

InteractiveViewer(
child: Image.asset(tiger),
minScale: 0.1,
),

3. boundaryMargin

Any transformation in the image that results in the viewport being able to view outside of the boundaries will instead be stopped at the boundaries,

This property helps us to keep a certain margin between the corners of the image and the viewport boundaries of our device

Example :

InteractiveViewer(
child: Image.asset(tiger),
boundaryMargin: EdgeInsets.all(5.0),
),

4. onInteractionEnd

A property that takes a ScaleEndDetails variable and lets you execute whatever function you want inside it, you can even print the details like

Example :

Column(
children: [
Expanded(
child: Center(
child: InteractiveViewer(
child: Image.asset(tiger),
boundaryMargin: EdgeInsets.all(5.0),
onInteractionEnd: (ScaleEndDetails endDetails) {
print(endDetails);
print(endDetails.velocity);
setState(() {
velocity = endDetails.velocity.toString();

});
},
),
),
),
Text(velocity)
],
),

you can access the velocity from the endDetails, now i have simply used it to display the velocity by which user is stretching the image.

5. controller

Just like Pageview Listview etc this widget also has a controller, It takes the value of TransformationController to be assigned to this widget

Example :

TransformationController controller = TransformationController();

Now using this you can do many changes with the transformationController but first you have to assign it.

InteractiveViewer(
child: Image.asset(tiger),
transformationController: controller,
boundaryMargin: EdgeInsets.all(5.0),
onInteractionEnd: (ScaleEndDetails endDetails) {
print(endDetails);
print(endDetails.velocity);
setState(() {
velocity = endDetails.velocity.toString();

});
},
),

After assigning it you can do something like reverting the image back to its original position after user is done stretching it, so for that we will use onInteractionEnd with the controller

Before we start, first you need to know that controller can access a special property called “value” which is of type Matrix4

(You might Need to research about matrices before diving straight into using them)

Now we can change the controller’s value inside onInteractionEnd like this

controller.value = Matrix4.identity();

Now what is Matrix4.identity()? Well its basically an identity matrix

Identity Matrix is this :

identity matrix

Now what it does it that it returns the controller to its original value, and that’s what our aim is to return the image to its normal size after user is done transforming it.

TransformationController controller = TransformationController();
String velocity = "VELOCITY";
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SafeArea(
child: Container(
child: Column(
children: [
Expanded(
child: Center(
child: InteractiveViewer(
child: Image.asset(tiger),
transformationController: controller,
boundaryMargin: EdgeInsets.all(5.0),
onInteractionEnd: (ScaleEndDetails endDetails) {
print(endDetails);
print(endDetails.velocity);
controller.value = Matrix4.identity();
setState(() {
velocity = endDetails.velocity.toString();

});
},
),
),
),
Text(velocity,style: TextStyle(
fontWeight: FontWeight.bold),)
],
),
),
),
),
);
}
auto resizing to default when you let go.

These are just basic and most used properties of Interactive Viewer widget, you can find more of them at the official documentation.

Hope you enjoyed reading through the wall of text and gif’s, let me know in comments if you face any problem. I will try my best to help you out.


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

Date and Time Picker In Flutter

0

In this article, we will explore the Date and Time Picker in a flutter. We will not be using any package in this application. We will use some core functions available in flutter to achieve this. We will implement a demo of the Date and Time Picker in your flutter applications.


Table of Contents :

Date And Time Picker

Code Implementation

Code File

Conclusion


Date And Time Picker

A date and time picker for a flutter, you can choose date/time / date&time in English, Dutch, and any other language you will want, and you can also custom your own picker content.

Demo Module ::

Demo.gif

Code Implementation

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

In this screen, You will be able to choose the date and time by tapping on them in your Application.

Future<Null> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime(2015),
lastDate: DateTime(2101));
if (picked != null)
setState(() {
selectedDate = picked;
_dateController.text = DateFormat.yMd().format(selectedDate);
});
}

Initialize DateTime pickers class.that will save our picked Date.

And in onTap of TextFromField, we call _selectDate function then the show will be shown the picker and save the picked date and time.

InkWell(
onTap: () {
_selectDate(context);
},
child: Container(
width: _width / 1.7,
height: _height / 9,
margin: EdgeInsets.only(top: 30),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.grey[200]),
child: TextFormField(
style: TextStyle(fontSize: 40),
textAlign: TextAlign.center,
enabled: false,
keyboardType: TextInputType.text,
controller: _dateController,
onSaved: (String val) {
_setDate = val;
},
decoration: InputDecoration(
disabledBorder:
UnderlineInputBorder(borderSide: BorderSide.none),
contentPadding: EdgeInsets.only(top: 0.0)),
),
),
),

It is just a _selectTime function, as shown down here.

Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if (picked != null)
setState(() {
selectedTime = picked;
_hour = selectedTime.hour.toString();
_minute = selectedTime.minute.toString();
_time = _hour + ' : ' + _minute;
_timeController.text = _time;
_timeController.text = formatDate(
DateTime(2019, 08, 1, selectedTime.hour, selectedTime.minute),
[hh, ':', nn, " ", am]).toString();
});}

Initializing TimeOfDay pickers class that will save our picked Time in _selecteTime Function.

On Tapping at TextFormField , We call a _selectTime Function which will show the date & time picker saving the picked time .

InkWell(
onTap: () {
_selectTime(context);
},
child: Container(
margin: EdgeInsets.only(top: 30),
width: _width / 1.7,
height: _height / 9,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.grey[200]),
child: TextFormField(
style: TextStyle(fontSize: 40),
textAlign: TextAlign.center,
onSaved: (String val) {
_setTime = val;
},
enabled: false,
keyboardType: TextInputType.text,
controller: _timeController,
decoration: InputDecoration(
disabledBorder:
UnderlineInputBorder(borderSide: BorderSide.none),
// labelText: 'Time',
contentPadding: EdgeInsets.all(5)),
),
),
),

Code File :

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class DateTimePicker extends StatefulWidget {
@override
_DateTimePickerState createState() => _DateTimePickerState();
}

class _DateTimePickerState extends State<DateTimePicker> {
double _height;
double _width;

String _setTime, _setDate;

String _hour, _minute, _time;

String dateTime;

DateTime selectedDate = DateTime.now();

TimeOfDay selectedTime = TimeOfDay(hour: 00, minute: 00);

TextEditingController _dateController = TextEditingController();
TextEditingController _timeController = TextEditingController();

Future<Null> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime(2015),
lastDate: DateTime(2101));
if (picked != null)
setState(() {
selectedDate = picked;
_dateController.text = DateFormat.yMd().format(selectedDate);
});
}

Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if (picked != null)
setState(() {
selectedTime = picked;
_hour = selectedTime.hour.toString();
_minute = selectedTime.minute.toString();
_time = _hour + ' : ' + _minute;
_timeController.text = _time;
_timeController.text = formatDate(
DateTime(2019, 08, 1, selectedTime.hour, selectedTime.minute),
[hh, ':', nn, " ", am]).toString();
});
}

@override
void initState() {
_dateController.text = DateFormat.yMd().format(DateTime.now());

_timeController.text = formatDate(
DateTime(2019, 08, 1, DateTime.now().hour, DateTime.now().minute),
[hh, ':', nn, " ", am]).toString();
super.initState();
}

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;
dateTime = DateFormat.yMd().format(DateTime.now());
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Date time picker'),
),
body: Container(
width: _width,
height: _height,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(
children: <Widget>[
Text(
'Choose Date',
style: TextStyle(
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w600,
letterSpacing: 0.5),
),
InkWell(
onTap: () {
_selectDate(context);
},
child: Container(
width: _width / 1.7,
height: _height / 9,
margin: EdgeInsets.only(top: 30),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.grey[200]),
child: TextFormField(
style: TextStyle(fontSize: 40),
textAlign: TextAlign.center,
enabled: false,
keyboardType: TextInputType.text,
controller: _dateController,
onSaved: (String val) {
_setDate = val;
},
decoration: InputDecoration(
disabledBorder:
UnderlineInputBorder(borderSide: BorderSide.none),
// labelText: 'Time',
contentPadding: EdgeInsets.only(top: 0.0)),
),
),
),
],
),
Column(
children: <Widget>[
Text(
'Choose Time',
style: TextStyle(
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w600,
letterSpacing: 0.5),
),
InkWell(
onTap: () {
_selectTime(context);
},
child: Container(
margin: EdgeInsets.only(top: 30),
width: _width / 1.7,
height: _height / 9,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.grey[200]),
child: TextFormField(
style: TextStyle(fontSize: 40),
textAlign: TextAlign.center,
onSaved: (String val) {
_setTime = val;
},
enabled: false,
keyboardType: TextInputType.text,
controller: _timeController,
decoration: InputDecoration(
disabledBorder:
UnderlineInputBorder(borderSide: BorderSide.none),
// labelText: 'Time',
contentPadding: EdgeInsets.all(5)),
),
),
),
],
),
],
),
),
);
}
}

Conclusion :

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

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

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