Flutter Firebase
Project Configuration Firebase Flutter
- Go to the Firebase site , and create an account there.
- In the firebase dashboard, go to the project summary menu or dashboard
- Click the plus button ,choose android or ios platform and Configure the project
- Put the google-service.json file into the folder project
/android/app/
and Configuration is complete.
Configure Auth or User Login
In Firebase , open the menu .Authentication Select tab Sign in method Activate the email.
Setting up the Library
provider: ^6.0.0
Link – For the state management
firebase_auth: ^3.1.0
Link – For the auth
firebase_core: ^0.5.0
Link – Core Package
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; Widget build(BuildContext context) { FirebaseAuth auth = FirebaseAuth.instance; return MaterialApp( routes: routes, title: 'My App Test', theme: ThemeData( primarySwatch: _theme.appColor, visualDensity: VisualDensity.adaptivePlatformDensity, ), initialRoute: auth.currentUser == null ? "/welcome" : "/home", ); }
Welcome Screen
import 'package:myapp/app/app_theme.dart'; import 'package:flutter/material.dart'; class WelcomeView extends StatelessWidget { final AppTheme _theme = new AppTheme(); @override Widget build(BuildContext context) { return _theme.page( context: context, content: Container( margin: EdgeInsets.only(left: 54, right: 54, bottom: 145), child: Column( mainAxisSize: MainAxisSize.min, children: [ Container( width: double.infinity, height: 33, child: RaisedButton( shape: _theme.buttonTheme(), onPressed: () { Navigator.pushReplacementNamed(context, '/auth', arguments: "register"); }, child: Text("Register Account"), ), ), Container( margin: EdgeInsets.only(top: 44), width: double.infinity, height: 33, child: RaisedButton( shape: _theme.buttonTheme(), onPressed: () { Navigator.pushReplacementNamed(context, '/auth', arguments: "login"); }, child: Text("Login"), ), ), ], ), ), ); } }
You Can use ElevatedButton instead of deprecated RaisedButton.
Auth View (Login and Register)
import 'dart:io'; import 'package:myapp/app/app_theme.dart'; import 'package:myapp/states/auth/auth_state.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class AuthView extends StatelessWidget { final AppTheme _theme = new AppTheme(); Widget _loading() { return Platform.isAndroid ? Container( child: Center( child: CircularProgressIndicator(), ), ) : Container( child: Center(child: CupertinoActivityIndicator()), ); } @override Widget build(BuildContext context) { String argument = ModalRoute.of(context).settings.arguments; String title = argument == "login" ? "Login" : "Register new account"; String buttonTitle = argument == "login" ? "Login" : "Create account"; return _theme.page( context: context, content: Container( width: double.infinity, padding: EdgeInsets.only(top: 44, right: 54, left: 54, bottom: 70), decoration: BoxDecoration( color: _theme.appColors[white], borderRadius: BorderRadius.only( topRight: Radius.circular(50), topLeft: Radius.circular(50), ), ), child: ChangeNotifierProvider( create: (c) => AuthState(argument, context), child: Consumer<AuthState>( builder: (c, state, _) => Form( key: state.key, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( title, style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold), ), Container( margin: EdgeInsets.only(top: 39, bottom: 39), child: TextFormField( decoration: InputDecoration(labelText: "Email"), validator: (value) => state.emailValidator(value), controller: state.email, ), ), Container( margin: EdgeInsets.only(top: 0, bottom: 55), child: TextFormField( controller: state.password, obscureText: true, validator: (value) => state.passwordValidator(value), decoration: InputDecoration(labelText: "Password"), ), ), state.authProcess ? _loading() : Container( width: double.infinity, child: RaisedButton( shape: _theme.buttonTheme(), color: _theme.appColor[900], textColor: _theme.appColors[white], onPressed: () { state.auth(); }, child: Text(buttonTitle), ), ), ], ), ), ), ), ), onTapBack: () { Navigator.pushReplacementNamed(context, '/welcome'); return; }, ); } }
Home Screen
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class HomeView extends StatelessWidget { final FirebaseAuth _auth = FirebaseAuth.instance; @override Widget build(BuildContext context) { return Scaffold( body: Container( margin: EdgeInsets.all(23), child: Stack( children: [ Center( child: Column( children: [ Row( children: [ Expanded( child: Container(), flex: 1, ), Expanded( flex: 6, child: GestureDetector( onTap: () { _auth.signOut().then((value) { Navigator.pushReplacementNamed( context, "/welcome"); }); }, child: Image.asset( 'assets/images/home.png', height: 201, width: 201, ), ), ), Expanded( child: Container(), flex: 2, ) ], ), Container( width: double.infinity, child: Text( "Welcome", style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), ), Padding(padding: EdgeInsets.only(top: 28)), Container( child: Text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Egestas scelerisque porttitor turpis viverra lobortis convallis. Libero tristique donec turpis elit", style: TextStyle(fontSize: 12), textAlign: TextAlign.center, ), ) ], mainAxisSize: MainAxisSize.min, ), ) ], ), ), ); } }
Auth State
import 'package:myapp/app/app_theme.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class AuthState with ChangeNotifier { bool authProcess = false; bool autoValidate = false; final TextEditingController email = TextEditingController(); final TextEditingController password = TextEditingController(); final key = GlobalKey<FormState>(); final String argument; final BuildContext context; final AppTheme _theme = new AppTheme(); AuthState(this.argument, this.context); auth() { if (key.currentState.validate()) { authProcess = true; notifyListeners(); if (argument == "register") _register(); else _login(); } else { autoValidate = true; notifyListeners(); } } FirebaseAuth _auth = FirebaseAuth.instance; _dialog(String message) { showDialog( context: context, child: AlertDialog( shape: _theme.buttonTheme(), content: Container( padding: EdgeInsets.all(16), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(40))), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( "Auth Failed", style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold), ), Padding(padding: EdgeInsets.only(top: 16)), Text(message), Container( margin: EdgeInsets.only(top: 16), width: 150, height: 40, child: RaisedButton( color: _theme.appColors[red], textColor: _theme.appColors[white], onPressed: () { Navigator.pop(context); }, child: Text("OK"), shape: _theme.buttonTheme(), ), ) ], ), ), )); } _login() { _auth .signInWithEmailAndPassword(email: email.text, password: password.text) .then((value) { authProcess = false; notifyListeners(); print("res ${value.user.email}"); Navigator.pushReplacementNamed(context, "/home"); }).catchError((err) { authProcess = false; notifyListeners(); print("res error $err"); _dialog(err.toString()); }); } _register() { _auth .createUserWithEmailAndPassword( email: email.text, password: password.text) .then((value) { authProcess = false; notifyListeners(); print("res ${value.user.email}"); Navigator.pushReplacementNamed(context, "/home"); }).catchError((err) { authProcess = false; notifyListeners(); print("res error $err"); _dialog(err.toString()); }); } String emailValidator(String value) { Pattern pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'; RegExp regex = new RegExp(pattern); if (!regex.hasMatch(value)) return 'Email format is incorrect'; else return null; } String passwordValidator(String value) { if (value.length < 6) return "Password minimal 6 character"; return null; } }
How to see users who have logged in and registered into our application.
-
Go to the Firebase site
-
Go to Authentication Menu and open the Users tab, and there is results.
-
You can also add according to your needs.