gpt4 book ai didi

firebase - Flutter + SharedPreferences:如何使用FutureBuilder

转载 作者:行者123 更新时间:2023-12-03 04:35:49 25 4
gpt4 key购买 nike

我正在尝试构建一个Wrapper()小部件,该小部件基于3个不同的因素返回LoginScreen或HomeScreen():

  • (如果用户为空)
  • (如果电子邮件已验证)
  • (如果应用程序是首次启动的)

  • 我的问题是Future不会被FutureBuilder触发...
    我该如何解决?泰

    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;
    }
    }
    }

    最佳答案

    您需要将hasAlreadyStarted方法分配给属性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();
    }
    });
    检查:
    https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

    关于firebase - Flutter + SharedPreferences:如何使用FutureBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64149683/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com