我一直在尝试根据我的共享首选项设置加载不同的页面,但没有成功。
根据 stackoverflow 中找到的几篇文章,我最终得到了以下解决方案:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:testing/screens/login.dart';
import 'package:testing/screens/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Widget page = Login();
Future getSharedPrefs() async {
String user = Preferences.local.getString('user');
if (user != null) {
print(user);
this.page = Home();
}
}
@override
void initState() {
super.initState();
this.getSharedPrefs();
}
@override
Widget build(BuildContext context) {
return MaterialApp(home: this.page);
}
}
class Preferences {
static SharedPreferences local;
/// Initializes the Shared Preferences and sets the info towards a global variable
static Future init() async {
local = await SharedPreferences.getInstance();
}
}
变量user
不为空,因为print(user)
返回预期的值,但是login
屏幕始终处于打开状态。
您的问题是您的构建方法在 getSharedPrefs 未来完成之前返回。 getSharedPrefs 一旦被调用就会立即返回,因为它是异步的,并且您通过不等待将其视为“即发即忘”。看到你不能在 initState 函数中等待,这是有道理的。
这是您要使用 FutureBuilder 小部件的地方。创建一个返回布尔值(或枚举,如果您想要更多状态)的 Future 并使用 future 构建器作为您的 home 子级以返回正确的小部件。
创造你的未来
Future<bool> showLoginPage() async {
var sharedPreferences = await SharedPreferences.getInstance();
// sharedPreferences.setString('user', 'hasuser');
String? user = sharedPreferences.getString('user');
return user == null;
}
当 user 为 null 时,这将返回 true。在 Future 构建器中使用这个 future 来监听值的变化并做出相应的响应。
@override
Widget build(BuildContext context) {
return MaterialApp(home: FutureBuilder<bool>(
future: showLoginPage(),
builder: (buildContext, snapshot) {
if(snapshot.hasData) {
if(snapshot.data){
// Return your login here
return Container(color: Colors.blue);
}
// Return your home here
return Container(color: Colors.red);
} else {
// Return loading screen while reading preferences
return Center(child: CircularProgressIndicator());
}
},
));
}
我运行了这段代码并且运行良好。当需要登录时,您应该看到蓝屏;当有用户存在时,您应该看到红屏。取消注释 showLoginPage 中的行以进行测试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)