Flutter popUntil throws Bad state: Future already

2019-06-23 19:41发布

问题:

This question already has an answer here:

  • Using Navigator.popUntil and route without fixed name 1 answer

I have screens A->B->C->D

In B, C, D screens there is a button that should take you to screen A keeping it's state (thus pushNamedAndRemoveUntil isn't appropriate here).

I want to use popUntil, that's how I do it, based on docs:

Navigator.popUntil(context, ModalRoute.withName(ScreenName.mainScreen));

I get an error: Bad state: Future already completed

Here is my main:

void main() {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  final pages = {
    ScreenName.mainScreen: (settings) => MaterialPageRoute(
        builder: (context) => MainScreen(), settings: settings),
  };

  var configureApp = AppConfig(
    appName: 'TaskerMate',
    flavorName: FLAVOR_NAME.PROD,
    child: AppModelProvider(
      model: AppModel(),
      child: MaterialApp(
        theme: TMTheme().get(),
        home: SplashScreen(),
        onGenerateRoute: (settings) {
          pages[settings.name](settings);
        },
        routes: {ScreenName.mainScreen: (context) => MainScreen()},
      ),
    ),
  );

  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });

  runApp(configureApp);
}

ScreenName.mainScreen -> static final String mainScreen = '/main';

回答1:

Took me ages to find the answer, but if anyone finds themselves stuck with this problem, Rémi Rousselet's answer to another question is what solved it for me:

 Navigator.pushReplacement(
  context,
  MaterialPageRoute(settings: RouteSettings(name: "Foo")),
);

Add settings to MaterialPageRoute with name, then call popUntil like so:

Navigator.popUntil(context, ModalRoute.withName("Foo"))


标签: dart flutter