Home > Software engineering >  How to return a widget if I need to go to a new screen?
How to return a widget if I need to go to a new screen?

Time:10-10

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();
            }
        }),
    );
 }

CodePudding user response:

There is a statement about your issue (Obviously, it does not like the use of Navigator stuff in the future builder.). Future.builder shouldn't include logic beyond building widgets (e.g. don't call Navigator.push).

Instead of FutureBuilder, you can just put the async call in build().

Widget build(BuildContext context) {

    check().then((success) {
      if (success) {
        Navigator.pushReplacementNamed(context, '/home');
      } else {
        Navigator.pushReplacementNamed(context, '/login');
      }
    });

You can learn more about this issue at this link: https://github.com/flutter/flutter/issues/16218

CodePudding user response:

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());
          }
        });
  }
}
  • Related