Home > Back-end >  How to pass arguments to pushReplacementNamed?
How to pass arguments to pushReplacementNamed?

Time:05-02

In my application, when the 'Next' button is clicked, pushReplacementNamed is fired and the arguments are passed to the next screen. How can I implement a route with arguments? Need exactly pushReplacementNamed. Here is an example code with push:

_changeColor(String color) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => ColorWidget(color: color),
      ),
    );
  }
  
  ...
  
    ElevatedButton(
              onPressed: () => _changeColor(selectedValue),
              child: const Text('Next'),
            )

How can one also pass arguments with pushReplacementNamed? My main.dart:

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
         '/': (context) => HomeScreenWidget(),
         '/color_picker': (context) => ColorPickerWidget(),
         '/text_value': (context) => TextValueScreen(),
       },
       initialRoute: '/',
    );
  }
}

CodePudding user response:

You have to send data in arguments key and get it back by route. Check this document https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments

CodePudding user response:

Simply use

var argument = 'example string';

Navigator.pushNamed(
    context,
    '/otherscreen',
    arguments: {'exampleArgument': argument},
);

and extract the arguments as follows:

@override
Widget build(BuildContext context) {
    final arguments = (ModalRoute.of(context)?.settings.arguments ?? <String, dynamic>{}) as Map;

    print(arguments['exampleArgument']);

    return Scaffold(...);
  • Related