How Flutter Keeps Logged In

Asked 2 years ago, Updated 2 years ago, 87 views

Prerequisites/What you want to achieve

Currently, I am learning about application development using Flutter+Firebase.
We would like to implement the following features as a consistent login feature:

  • Transition to the login page and log in only when logging in for the first time
  • Unless you log out, you will not transition to the login page even if you open the app after you exit the app

I did some research in my own way and tried them, but I didn't go to the login page in the first place.
The code I tried is the main code below.

How can we implement these functions as a concrete method?
Also, I am currently implementing features using Firebase's Email and Password, but is this a common way to implement these features even for Google and Facebook logins?

I am a beginner at Flutter, so I would appreciate it if you could let me know.

What is currently being implemented

  • Login with FirebaseAuth
  • Database using FirebaseCloudStore

Tried

  • Verifying Login Status Using CurrentUser in FirebaseAuth

Supplementary information (for example, FW/Tool Version)

what you used

  • FirebaseAuth
  • FirebaseCloudStore
class MyApp extensions StatelessWidget{
  // This widget is the root of your application.

  final UserState user=UserState();

  @override
  Widget build (BuildContext context) {
    return ChangeNotifierProvider<UserState>.value(
        value —user,
        child —MaterialApp(
          // Hide Debug Labels
          debugShowCheckedModeBanner: false,
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwitch:Colors.blue,
            visualDensity —VisualDensity.adaptivePlatformDensity,
          ),
          home —LoginPage(),
          initialRoute: "/",
          routes —<String, WidgetBuilder>{
//            " / " : (BuildContext context) = > LoginPage(),
            AddRecord.routeName: (BuildContext context) = > AddRecord(),
            "/login" : (BuildContext context) = > LoginPage(),
            "/home": (BuildContext context) = > PageManager()
          },
        )
    );
  }
}

class LoginCheck extensions StatefulWidget {
  LoginCheck ({Key}):super(key:key);

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

}

class_LoginCheckState extensions State<LoginCheck>{

  @override
  void initState() {
    super.initState();
    checkUser();

    // TODO:implementation initState


  }
  void checkUser()async {
    final UserState userState=Provider.of<UserState>(context);
    final currentUser=wait FirebaseAuth.instance.currentUser();
    print(currentUser);
    if(currentUser==null){
      Navigator.pushReplacementNamed(context, "/login");
    } else {
      userState.setUser(currentUser);
      Navigator.pushReplacementNamed(context, "/home");
    }
  }
  @override
  Widget build (BuildContext context) {
    // TODO:implementation build
    US>return Scaffold(
      body: Center(
        child —Container(
          child: Text("Loading..."),
        ),
      ),
    );
  }
}

firebase flutter dart

2022-09-30 14:39

1 Answers

Do you initialize Firebase in the first place?
If you use FirebaseSDK, you must do Firebase.initialize when starting the application

import'package:flutter/material.dart';

// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(App());
}

class App extensions StatelessWidget {
  // Create the initialization Future outside of `build`:
  final Future<FirebaseApp>_initialization=Firebase.initializeApp();

  @override
  Widget build (BuildContext context) {
    US>return FutureBuilder(
      // Initialize FlutterFire:
      future:_initialization,
      builder: (context, snapshot) {
        // Check for errors
        if(snapshot.hasError){
          return SomethingWentWrong(); // Error Page
        }

        // Once complete, show your application
        if(snapshot.connectionState==ConnectionState.done){
        // Put the main body of the app here
          return MyAwesomeApp();
        }

        // Otherwise, show something while waiting for initialization to complete
        return Loading(); // Progress Indicator
      },
    );
  }
}

https://firebase.flutter.dev/docs/overview
こちらDetails are provided here

Below is an example of a CurrentUser decision

FirebaseAuth.instance
  .authStateChanges()
  .listen(User user){
    if(user==null){
      print('User is currently signed out!');
    } else{
      print('User is signed in!');
    }
  });

As long as you don't log out, even if you open the app after you close it, it won't transition to the login page

Fi FirebseSDK automatically perpetuates login


2022-09-30 14:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.