What I'm trying to do is to show a widget with loading status while I'm fetching some info from the web using the http client. Then based on the result to automatically navigate to a different route.
Here is my code:
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: FutureBuilder(
future: http.get("https://exmaple.com"),
builder: (BuildContext context, AsyncSnapshot<http.Response> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('ConnectionState.none.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
// Navigator.pushNamed(context, '/route2');
return Text('Result: ${snapshot.data.statusCode}');
}
}
return null; // unreachable
},
)));
}
}
The problem is that if I add Navigator.pushNamed(context, '/route2');
it will throw an error.
I understand why it is throwing the error. What I don't know is how to achieve this. All examples that I found showed that navigation happens after some user iteration onPressed
.
You can use a simple hack to make the code work.
// else
Future.delayed(const Duration(milliseconds: 0))
.then((value) => Navigator.pushNamed(context, '/route2'));
return Text('Result: ${snapshot.data.statusCode}');
// end else
Make your widget stateful and use initState function to make request to server:
@override
void initState() {
super.initState();
http.get("https://exmaple.com").then((v) => Navigator.of(context).pushNamed('/route2'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With