Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Pass Data Back with .popUntil

I have been using Navigator.pop and passing data back 1 screen with ease. However, if I use Navigator.popUntil, what is an acceptable way to pass an object back to the destination screen?

like image 718
Josh Kahane Avatar asked Aug 29 '18 10:08

Josh Kahane


People also ask

How do you send data back in flutter?

To return data to the first screen, use the Navigator. pop() method, which accepts an optional second argument called result . Any result is returned to the Future in the SelectionButton.

How do you use the Navigator popAndPushNamed in flutter?

To use popAndPushNamed, a Navigator. onGenerateRoute callback must be provided. Returns a Future that completes to the result value passed to pop when the pushed route is popped off the navigator. The provided arguments are passed to the pushed route via RouteSettings.


1 Answers

You can using arguments in RouteSettings to pass data back to a specific Route.

For example:


// in MaterialApp
MaterialApp(
   onGenerateRoute: (settings) {
      switch (settings.name) {
         case '/':
            return MaterialPageRoute(
                     settings: RouteSettings(name: '/', arguments: Map()),  // (1)
                     builder: (_) => HomePage()
                  );
      }
   }
)

// in HomePage
Navigator.of(context).push(MaterialPageRoute(builder: (_) => StuffPage())
                     .then(_) {
                        final arguments = ModalRoute.of(context).settings.arguments as Map;
                        final result = arguments['result'];
                     };

// in StuffPage
Navigator.of(context).popUntil((route) {
   if (route.settings.name == '/') {
      (route.settings.arguments as Map)['result'] = 'something';
      return true;
   } else {
      return false;
   }
});

Note that: you have to initialize arguments or it will be null, that's what is the purpose of (1)

like image 105
hunghd Avatar answered Sep 18 '22 09:09

hunghd