Search code examples
flutterflutter-futurebuilder

How to return a widget if I need to go to a new screen?


Why do this code in not properly set up? I get the error: This function has a return type of 'Widget', but doesn't end with a return statement.

Obviously, it doesn like the use of Navigator stuff in future builder. How to make it properly?

MaterialApp(
    home: const Splash1(),
);

class Splash1 extends StatelessWidget {
  const Splash1({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<bool>(
          future: checkIsSeen(),
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            if (snapshot.hasData) {
              if (snapshot.data == true) {
                Navigator.pushReplacement(context,
                  MaterialPageRoute(builder: (context) => const HomeView()),
                );
              } else {
                Navigator.pushReplacement(context,
                  MaterialPageRoute(builder: (context) => const IntroScreen()),
                );
              }
            } else if (snapshot.hasError) {
              return const Icon(
                  Icons.error_outline,
                  size: 60,
              );
            } else {
              return CircularProgressIndicator();
            }
        }),
    );
 }

Solution

  • Since HomeView and IntroScreen both contain a Scaffold, you can reorganise your code like this, without using Navigator in the build method:

    class Splash1 extends StatelessWidget {
      const Splash1({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder<bool>(
            future: checkIsSeen(),
            builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
              if (snapshot.hasData) {
                return snapshot.data ? const HomeView() : const IntroScreen();
              } else {
                return Scaffold(
                    body: snapshot.hasError
                        ? const Icon(
                            Icons.error_outline,
                            size: 60,
                          )
                        : const CircularProgressIndicator());
              }
            });
      }
    }