Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The user get logout after closing the application #1

Open
atta1234 opened this issue Apr 30, 2021 · 2 comments
Open

The user get logout after closing the application #1

atta1234 opened this issue Apr 30, 2021 · 2 comments

Comments

@atta1234
Copy link

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

@techguydev
Copy link

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

@RikoDEV
Copy link

RikoDEV commented Jul 6, 2022

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();
                }
              },
            )
        ),
      )
    );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants