class TodoList extends ChangeNotifier{Future<bool> GetLoginData() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
notifyListeners();
return prefs.getBool('data')??false;
}}
class _CheckState extends State<Check> {
Widget build(BuildContext context) {
final x = Provider.of<TodoList>(context);
print(x.GetLoginData().toString());
return FutureBuilder<bool>(
future: x.GetLoginData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
return (snapshot.data == true) ? Main() : Login();
}
});
}
}
没有从 getlogindata() 函数的未来获得任何值,该函数是异步的,并假设从本地数据库返回一个布尔值,并且该函数是在 Provider 中实现的。我该如何解决该问题?
要解决此问题,请删除
notifyListeners();
内的 GetLoginData
。这导致 _CheckState
的 build
方法重新构建,因为 final x = Provider.of<TodoList>(context);
正在侦听更改。
如果您想保留
notifyListers();
,另一种选择是使用 Provider.of<TodoList>(context, listen: false)
或 read 方法