我正在尝试构建一个Wrapper()
小部件,该小部件根据3种不同的因素返回LoginScreen或HomeScreen():
我的问题是Future不会被FutureBuilder触发...
我该如何解决? 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;
}
}
}
答案 0 :(得分:1)
您需要将方法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