skip to Main Content
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


  1. 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

    Login or Signup to reply.
  2. Because you didn’t wait to get the complete result

       print(x.GetLoginData().toString());
    

    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 as async 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:

      void printFutureValue(BuildContext context)async{
       
         final x = Provider.of<TodoList>(context);
           
         print(await  x.GetLoginData());
        
      }
    
    @override
    Widget build(BuildContext context){
    printFutureValue();
    ......
    }
    

    Hope it helps you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search