I am trying to navigate after login inside futurebuilder. api request done successfully but navigation getting error while testing. Help me How to use futurebuilder properly.
child: ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_mobileKey.currentState!.validate()) {
FutureBuilder<Loginuser>(
future: loginuser(mobileController.text.toString(),
passwordController.text.toString()),
builder: (context, snapshot) {
if (snapshot.hasData) {
context.go('/Home');
return Text(snapshot.data!.message);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
);
}
context.go('/Home');
},
child: const Text('Submit')),
I tried this its not working. I am using " go_router: ^5.2.4 " for navigation
3
Answers
This method help you to navigate the route without FutureBuilder. see the code
TLDR: Add:
to the
FutureBuilder
I managed to reproduce the problem with this example. Let’s take a look.
If you run this code:
You’ll see an error:
So, to fix the problem, you need to use
WidgetsBinding.instance.addPostFrameCallback
:but for your example for
go_router
, add this line:Complete working example:
See also
setState() or markNeedsBuild called during build
Try removing the
FutureBuilder
from inside theElevatedButton
instead usePromises
i.ethen/catch
to navigate to new screenUpdated code: