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();
}
});
}
}
Not getting any value from future of getlogindata() function which is asynchronus and suppose to return me a boolean value from local database and this function is implemented within Provider.How can i resolve the issue?
2
Answers
To resolve the issue remove the
notifyListeners();
inside theGetLoginData
. This is causing the_CheckState
‘sbuild
method to re-build becausefinal x = Provider.of<TodoList>(context);
is listening for changes.Another option if you want to keep
notifyListers();
is to useProvider.of<TodoList>(context, listen: false)
or the read methodBecause you didn’t wait to get the complete result
This line of code shouldn’t print any thing except a promise of Future boolean value
Instance of Future<bool>
.because you didn’t wait to get the complete result. use
await
before calling that function, but using await requires marking the build method asasync
function which violates the overriding rules.Until now, I suppose your app is successfully run and displays a Main screen or login screen if the user is a new one.
but your problem still in that line, so make a helper method that prints its value:
Hope it helps you.