简体   繁体   中英

Flutter + SharedPreferences: how to use FutureBuilder

I'm trying to build a Wrapper() widget that return either the LoginScreen or the HomeScreen() based on 3 different factors:

  1. if the user is null or not
  2. if the email is verified or not
  3. if the app is on it's first start or not

The problem I have is that the Future doesn't get triggered by the FutureBuilder...

How can I solve this ? Ty

 import 'package:client/providers/auth_provider.dart'; import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../screens/home_screen.dart'; import '../screens/login_screen.dart'; class Wrapper extends StatefulWidget { @override _WrapperState createState() => _WrapperState(); } class _WrapperState extends State<Wrapper> { FirebaseAuth auth = FirebaseAuth.instance; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return FutureBuilder(builder: (context, snapshot) { if (snapshot.data == true) { return Provider.of<User>(context) != null && snapshot.hasData == true && AuthProvider().isEmailVerified ? HomeScreen() : LoginScreen(); } else { return LoginScreen(); } }); } Future<bool> hasAlreadyStarted() async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); if (prefs.getBool("first_run") == null || prefs.getBool("first_run") == true) { print(prefs.getBool("first_run")); prefs.setBool("first_run", false); return false; } else { print(prefs.getBool("first_run")); return true; } } catch (error) { print("error"); return false; } } }

You need to assign the method hasAlreadyStarted to the property future :

return FutureBuilder(future: hasAlreadyStarted(),
   builder: (context, snapshot) {
      if (snapshot.data == true) {
        return Provider.of<User>(context) != null &&
                snapshot.hasData == true &&
                AuthProvider().isEmailVerified
            ? HomeScreen()
            : LoginScreen();
      } else {
        return LoginScreen();
      }
    });

Check:

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM