Aman Nafiz
Aman Nafiz

Reputation: 11

Why is there Error getting value from FutureBuilder?

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?

Upvotes: 0

Views: 47

Answers (1)

Vladimir Gadzhov
Vladimir Gadzhov

Reputation: 824

To resolve the issue remove the notifyListeners(); inside the GetLoginData. This is causing the _CheckState's build method to re-build because final x = Provider.of<TodoList>(context); is listening for changes.

Another option if you want to keep notifyListers(); is to use Provider.of<TodoList>(context, listen: false) or the read method

Upvotes: 0

Related Questions