Flutter login with Provider :In flutter app UI represents the current state of the app so when there is any change .update the UI will rebuild from scratch we will be covering this scenario in Flutter login with Provider tutorial.
When there is a update to UI every widget in the screen i.e.
Text widgets, buttons and all the remaining things gets update.Usage of state management will decrease the code complexity and reduce code size.
For any dynamic app there will be quite a few changes almost on every interaction.
sometimes so making use of provider makes it much easy in app development.
State management :
State management provides the ability to handle data while page refresh. components to be aware of state these things provide much impact on the app performance.
We will be dealing with the concept of state management in flutter programming and consider Flutter login with Provider pattern and implement login mechanism in this tutorial.
pubspec.yaml :
Add provider, get dependency to pubspec.yaml to get start with flutter login with provider. Also try to specify the version numbers latest available to avoid any conflict.
provider: ^6.1.1
http: ^1.1.2
Authentication:
We will create a model class extending change notifier and specify the fields email, password.So that we can add the user credentials and fetch them any where in the app after login with provider.
Create a method to store the data and can also create a method to fetch the data.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:loginpro/constants/api.dart';
import 'package:loginpro/screens/Home.dart';
import 'package:loginpro/widgets/Navigate.dart';
import 'package:loginpro/widgets/Toast.dart';
class AuthenticationProvider extends ChangeNotifier {
final requesturl = Api.baseurl;
bool _isloading = false;
// String _resMessage = '';
//Getter
bool get isloading => _isloading;
// String get resMessage => _resMessage;
//Login
Future<void> LoginUser({
required email,
required password,
BuildContext? context,
}) async {
_isloading = true;
notifyListeners();
var url = '$requesturl/login';
var data = {
"email": email,
"password": password,
};
print(data);
var urlparse = Uri.parse(url);
http.Response response = await http.post(
urlparse,
body: data,
);
if (response.statusCode == 200 || response.statusCode == 201) {
// ignore: unused_local_variable
var response_data = json.decode(response.body.toString());
_isloading = false;
notifyListeners();
NavigatePage(context: context).NextPage(Page: const HomePage());
toastInfo(mesg: 'Login Successful');
} else {
_isloading = false;
notifyListeners();
toastInfo(mesg: 'Login Failed');
}
}
void clear() {
// _resMessage = "";
// _isLoading = false;
notifyListeners();
}
}
Loginpage :
Create a Login screen which will be loaded once the use is logged-in.And here we display information regarding the user base on provider pattern.
import 'package:flutter/material.dart';
import 'package:loginpro/auth/auth.dart';
//import 'package:loginpro/screens/Home.dart';
import 'package:loginpro/screens/Register.dart';
import 'package:loginpro/widgets/Button.dart';
import 'package:loginpro/widgets/Navigate.dart';
import 'package:loginpro/widgets/Textfield.dart';
//import 'package:loginpro/widgets/toast.dart';
import 'package:provider/provider.dart';
class Login extends StatefulWidget {
const Login({super.key});
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
final GlobalKey<FormState> formkey = GlobalKey<FormState>();
// bool _passVisibility = true;
// bool isEmailCorrect = false;
TextEditingController email = TextEditingController();
TextEditingController password = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: const Text(
"Login",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
body: Form(
key: formkey,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: [
Textfield(
title: 'Email',
controller: email,
hint: 'Enter your email',
label: 'Enter your email',
validatorvalue: 'Enter your email',
maxLines: 1),
Textfield(
title: 'Password',
controller: password,
hint: 'Enter your password',
label: 'Enter your password',
validatorvalue: 'Enter your password',
maxLines: 1),
const SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(10),
child: Consumer<AuthenticationProvider>(
builder: (context, auth, c) {
return Button(
text: 'Login',
click: () {
auth.LoginUser(
context: context,
email: email.text.trim(),
password: password.text.trim());
},
context: context,
status: auth.isloading);
}),
),
const SizedBox(
height: 10,
),
GestureDetector(
child: const Text(
'Register',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
onTap: () {
NavigatePage(context: context)
.NextPage(Page: const Register());
},
)
],
),
),
),
);
}
}
main.dart :Flutter login with Provider
Specify the providers inside the void main block of code as below.
import 'package:flutter/material.dart';
import 'package:loginpro/auth/auth.dart';
import 'package:loginpro/screens/splash.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => AuthenticationProvider())
],
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const SplashScreen(),
),
);
}
}
Specify the provider using which we try to save the information inside the onPressed
Consumer<AuthenticationProvider>(
builder: (context, auth, c) {
return Button(
text: 'Login',
click: () {
auth.LoginUser(
context: context,
email: email.text.trim(),
password: password.text.trim());
},
context: context,
status: auth.isloading);
}),
For More : To know about Playstore App Featured Screen using Flutter.
Leave a Reply