How to save user sign-in details in Flutter? How to save user sign-in details in Flutter? flutter flutter

How to save user sign-in details in Flutter?


Create a sqlite table and then when authenticating user is successful from server save required details to local table (delete any previous row saved before saving).

Now just check on app start that whether user table is empty or not and decide where the flow should be.

On first run table will be empty by default so it will show login page

APP RUN -> Check if row exists in user tableif YES ->  return Home();else -> return SignIn();


Use user sessions instead. Check out FlutterSession. The package adds user session support in Flutter and is easy to use.

bool isAuth = Authenticate({this.authenticateEmail, this.authenticatePassword});// Store value to sessionawait FlutterSession().set("isAuth", isAuth);// Retrieve item from sessiondynamic token = await FlutterSession().get("isAuth");


The root widget which you are calling Authentication is the app.

In pubspec.yaml add two dependencies

provider: ^4.0.3shared_preferences: ^0.5.6+1

Similar to the example, I wrote on Flutter provider state management, logout concept.

import 'package:flutter/material.dart';import 'package:provider/provider.dart';import 'package:shared_preferences/shared_preferences.dart';// If successful, returns a token. Otherwise throws an error.typedef Future<String> SignIn({  @required final String username,  @required final String password,});// If successful, returns void. Otherwise throws an error.typedef Future<void> SignOut({  @required final String token,});// ----------------------------------------------------------------------------class Session with ChangeNotifier {  String _token; // can be null  final SignIn _signIn;  final SignOut _signOut;  Session({    @required String token,    @required SignIn signIn,    @required SignOut signOut,  })  : assert(signIn != null),        assert(signOut != null),        this._token = token,        this._signIn = signIn,        this._signOut = signOut;  Future<void> signIn({    @required final String username,    @required final String password,  }) async {    assert(username != null);    assert(password != null);    final String token = await this._signIn(      username: username,      password: password,    );    this._token = token;    this.notifyListeners();  }  Future<void> signOut() async {    await this._signOut(token: this._token);    this._token = null;    this.notifyListeners();  }  bool get isAuthenticated {    return (this._token != null);  }}// ----------------------------------------------------------------------------Future<void> main() async {  // The app would load and present an error message on screen to add the following line.  // https://github.com/flutter/flutter/issues/39620  // https://api.flutter.dev/flutter/widgets/WidgetsFlutterBinding/ensureInitialized.html  WidgetsFlutterBinding.ensureInitialized();  // Initialize some local persistence.  // Could be SQLite or somewhere encrypted.  SharedPreferences prefs = await SharedPreferences.getInstance();  final Session session = Session(    token: prefs.getString('token'),    signIn: ({      @required final String username,      @required final String password,    }) async {      assert(username != null);      assert(password != null);      // Contact the server to validate credentials and get token.      await Future.delayed(Duration(milliseconds: 500)); // network delay      if ((username != 'johnsmith') || (password != 'opensesame')) {        throw new Exception("bad username or password");      } else {        final String token = '9djdhy89032jfdhdf70912';        // Store the token locally.        prefs.setString('token', token);        return token;      }    },    signOut: ({@required final String token}) async {      assert(token != null);      // Contact the server to sign out.      await Future.delayed(Duration(milliseconds: 500)); // network delay      // Update the local storage.      prefs.setString('token', null);    },  );  return runApp(    MultiProvider(      providers: [        ChangeNotifierProvider<Session>.value(value: session),      ],      child: MyApp(),    ),  );}class MyApp extends StatelessWidget {  @override  Widget build(final BuildContext context) {    return Consumer<Session>(      builder: (final BuildContext context, final Session session, final Widget child) {        return MaterialApp(          title: 'Flutter Demo',          theme: ThemeData(primarySwatch: Colors.blue),          home: session.isAuthenticated ? MyHomePage() : MySignInPage(),        );      },    );  }}class MyHomePage extends StatelessWidget {  @override  Widget build(final BuildContext context) {    return Scaffold(      appBar: AppBar(title: const Text("Home [Auth Protected]")),      body: Center(        child: RaisedButton(          child: const Text("Sign Out"),          onPressed: () {            final Session session = Provider.of<Session>(context, listen: false);            session.signOut();          },        ),      ),    );  }}// Of course this would have username and password inputs and a submit button.class MySignInPage extends StatelessWidget {  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(title: const Text("Sign In")),      body: Center(        child: RaisedButton(          child: const Text("Sign In with johnsmith, opensesame"),          onPressed: () {            final Session session = Provider.of<Session>(context, listen: false);            session.signIn(username: 'johnsmith', password: 'opensesame');          },        ),      ),    );  }}