Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter FutureBuilder and navigation to a different route using Navigator.pushNamed

Tags:

flutter

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 .

like image 272
Doua Beri Avatar asked Sep 11 '25 01:09

Doua Beri


2 Answers

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
like image 156
A0__oN Avatar answered Sep 13 '25 14:09

A0__oN


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'));
  }
like image 41
Igor Kharakhordin Avatar answered Sep 13 '25 14:09

Igor Kharakhordin