Provider merupakan salah satu State Management pada Flutter. Apa itu State Management? State Management merupakan sebuah cara untuk memisahkan antara logic dan view, sehingga logic tersebut bisa digunakan kembali atau re-usable di class yang berbeda. Berikut contoh penggunaan Provider pada halaman Login.
- Setelah membuat project baru pada Flutter, tambahkan plugin berikut pada depedencies pubspec.yaml lalu klik pub get
http: ^0.13.3 provider: ^6.0.1 |
- Tambahkan file baru dengan nama login.dart
Tampilan UI Login :
import ‘dart:ui’; import ‘package:email_validator/email_validator.dart’; import ‘package:flutter/cupertino.dart’; import ‘package:flutter/material.dart’; import ‘package:fluttertoast/fluttertoast.dart’; import ‘package:provider/provider.dart’; import ‘package:sakolaapp/provider/login_provider.dart’; import ‘package:sakolaapp/ui/register.dart’; import ‘package:shared_preferences/shared_preferences.dart’; import ‘lupapassword.dart’; class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { GlobalKey<FormState> formKey = GlobalKey<FormState>(); bool _obscureText = true; bool? rememberMe = false; LoginProvider? loginProvider; void _onRememberMeChanged(bool? newValue) => setState(() { rememberMe = newValue; if (rememberMe==true) { print(‘clicked’); } } else { // TODO: Forget the user } }); void _togglePasswordView() { setState(() { _obscureText = !_obscureText; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xffDEE6E8), body: Padding( padding: EdgeInsets.only( bottom: 20, top: 40, left: 20, right: 20, ), child: Form( key: formKey, child: SingleChildScrollView( child: Column( children: <Widget>[ SizedBox( height: 20, ), Align( alignment: Alignment.topLeft, child: Container( child: Text( ‘Login’, style: TextStyle( color: Colors.black, fontFamily: “Poppins”, fontStyle: FontStyle.normal, fontSize: 34, ), ), ), ), Align( alignment: Alignment.topLeft, child: Container( child: Text( ‘Silahkan Masuk’, style: TextStyle( color: Colors.black, fontFamily: “Poppins”, fontStyle: FontStyle.normal, fontSize: 24, ), ), ), ), SizedBox( height: 50.0, ), TextFormField( keyboardType: TextInputType.emailAddress, decoration: InputDecoration( labelStyle: TextStyle(fontSize: 20), hintText: “Email”, fillColor: Colors.white, filled: true, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( color: Color(0xff267ac0), ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide(color: Colors.white, width: 0), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), // contentPadding: EdgeInsets.all(20), ), autofillHints: [AutofillHints.email], validator: (email) => email != null && !EmailValidator.validate(email) ? ‘Enter a valid email’ : null, ), SizedBox( height: 10.0, ), Container( // margin: EdgeInsets.symmetric(horizontal: 20, vertical: 1), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), ), child: TextFormField( obscureText: _obscureText, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide(color: Colors.white, width: 0), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( color: Color(0xff267ac0), ), ), hintText: “Password”, border: InputBorder.none, suffixIcon: InkWell( onTap: _togglePasswordView, child: Icon( _obscureText ? Icons.visibility_off : Icons.visibility, color: Color(0xff267ac0), )), contentPadding: EdgeInsets.all(20), ), ), ), Container( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( child: Row( children: [ Checkbox( value: rememberMe, onChanged: _onRememberMeChanged ), Text( ‘Ingat Saya’, style: TextStyle( fontFamily: “Nunito”, color: Colors.black, fontSize: 14, ), ), ], )), SizedBox( height: 16, ), FlatButton( child: Text( ‘Lupa password ?’, style: TextStyle( fontFamily: “Nunito”, color: Colors.black, fontSize: 14, ), ), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => LupaPassword())); }, ), ], ), ), Container( alignment: Alignment.center, height: 46, child: ElevatedButton( style: ElevatedButton.styleFrom( primary: Color(0xff267ac0), textStyle: TextStyle(fontSize: 14), minimumSize: Size.fromHeight(40), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10)), ), child: value.loadingLogin ? SizedBox( height: 20, width: 20, child: CircularProgressIndicator( color: Colors.white), ) : Text(‘Masuk’), onPressed: () { } }, ), ), Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( ‘Belum punya akun ?’, style: TextStyle( color: Colors.black, fontFamily: “Nunito”, fontSize: 14, ), ), FlatButton( textColor: Colors.black, child: Text( ‘Buat akun’, style: TextStyle( fontFamily: “Nunito”, fontWeight: FontWeight.w600, fontSize: 14), ), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => Register())); }, ), ], ), ), Container( padding: EdgeInsets.all(50), alignment: Alignment.center, child: Text( ‘atau Lanjutkan dengan’, style: TextStyle( fontFamily: “Nunito”, color: Colors.black, fontSize: 14), ), ), Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 35, width: 35, child: InkWell( onTap: () {}, child: CircleAvatar( child: Image.asset(‘assets/images/FB.png’, height: 30, width: 30), backgroundColor: Colors.white, ), ), ), SizedBox( width: 10.0, ), Container( height: 35, width: 35, child: InkWell( onTap: () {}, child: CircleAvatar( // onPressed: () {}, // heroTag: null, child: Image.asset(‘assets/images/Google.png’, height: 24, width: 24), backgroundColor: Colors.white, ), ), ), ], ), ), ], ), ), ), ); } } |
- Setelah menyiapkan UI, selanjutnya tambahkan file dart baru dengan nama login_provider.dart.
import ‘dart:convert’; import ‘dart:developer’; import ‘package:flutter/material.dart’; import ‘package:http/http.dart’ as http; import ‘package:sakolaapp/home/home.dart’; import ‘package:shared_preferences/shared_preferences.dart’; class LoginProvider extends ChangeNotifier { TextEditingController email = new TextEditingController(); TextEditingController password = new TextEditingController(); TextEditingController rememberme = new TextEditingController(); bool loadingLogin = false; Future<void> login(BuildContext context) async { if (email.text.isEmpty || password.text.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(‘Email atau password tidak boleh kosong’))); return; } loadingLogin = true; notifyListeners(); http.Response res = await http.post( Uri.parse(your link Api is here), body: {“email”: email.text, “password”: password.text}, ); loadingLogin = false; notifyListeners(); if(res.statusCode == 200){ log(res.body); Map data = jsonDecode(res.body); if(data[‘isSuccess’] != false){ log(“success”); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context){ return HomePage(); })); }else if(data[‘isSuccess’] == false){ ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(“Email atau password salah”),) ); print(‘failed’); } } } } |
Pada class Provider ini terdapat controller untuk TextEditingController yang nantinya akan digunakan di controller TextFormField pada halaman Login.
- Pada UI Login tambahkan properti Provider yaitu Consumer dan Change Notifier
- Terakhir, pada controller TextFormField email dantambahkan nama controller yang di set pada class LoginProvider
Sekian untuk artikel kali ini, Semoga Bermanfaat, Terima kasih ^ ^