sanctum-flutter-app icon indicating copy to clipboard operation
sanctum-flutter-app copied to clipboard

The user get logout after closing the application

Open atta1234 opened this issue 3 years ago • 2 comments

How to keep the user loggedin until he want to logout in,,,

atta1234 avatar Apr 30 '21 17:04 atta1234

@atta1234 I am having the same problem, have you able to solve it?

techguydev avatar Jan 25 '22 22:01 techguydev

Take a look at https://github.com/unlikenesses/sanctum-flutter-app/blob/master/lib/auth.dart#L10. When initializing the application, check if the token still exists in shared_preferences. If so, change the value of _isAuthenticated to true.

auth.dart

refreshAuthState() async {
  String? token = await getToken();
  if (token != null) {
    _isAuthenticated = true;
  }
}

main.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './books.dart';
import './auth.dart';
import './login.dart';

void main() {
  runApp(
      ChangeNotifierProvider(
        create: (BuildContext context) => AuthProvider(),
        child: App(),
      )
  );
}

class App extends StatefulWidget {
  const App({Key? key}) : super(key: key);

  @override
  _AppState createState() => _AppState();

}

class _AppState extends State<App> {

  @override
  void initState() {
    // Check if the token still exists and update _isAuthenticated
    // used in Consumer<AuthProvider> builder
    Provider.of<AuthProvider>(context, listen: false).refreshAuthState();
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sanctum Books',
      home: new Scaffold(
        body: Center(
            child: Consumer<AuthProvider>(
              builder: (context, auth, child) {
                switch (auth.isAuthenticated) {
                  case true:
                    return BookList();
                  default:
                    return LoginForm();
                }
              },
            )
        ),
      )
    );
  }
}

RikoDEV avatar Jul 06 '22 09:07 RikoDEV