marc
marc

Reputation: 29

I am using flutter version 3.3.5. and I am getting this error message "Do not use BuildContexts across async gaps." for the code below

httpErrorHandle(
        response: res,
        context: context,
        onSuccess: () async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          Provider.of<UserProvider>(context, listen: false).setUser(res.body);
          await prefs.setString('x-auth-token', jsonDecode(res.body)['token']); 

       
            Navigator.pushNamedAndRemoveUntil(
            context,
            HomeScreen.routeName,
            (route) => false,
          );

        },
      );

I didn't find any solution related, this code is crashing the application

Upvotes: 2

Views: 440

Answers (1)

Etornam
Etornam

Reputation: 493

httpErrorHandle(
        response: res,
        context: context,
        onSuccess: () async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          Provider.of<UserProvider>(context, listen: false).setUser(res.body);
          await prefs.setString('x-auth-token', jsonDecode(res.body)['token']); 

            //if you are using a statefulWidget do:
            if(!mounted) return;

           //if it is a statelessWidget do:
           if(!context.mounted) return;
       
            Navigator.pushNamedAndRemoveUntil(
            context,
            HomeScreen.routeName,
            (route) => false,
          );

        },
      );

Upvotes: 2

Related Questions