UndercoverCoder
UndercoverCoder

Reputation: 1013

How can I use the arguments passed with pushNamed?

Say I have two routes /firstRoute and /secondRoute, both for the widgets FirstRoute and SecondRoute respectively. I'm pushing a named route onto the stack with some arguments, like so...

Navigator.pushNamed(
    context,
    "/secondRoute",
    arguments: <String, String>{"key" : "value"},
)

How can I now use this value in the SecondRoute? Looked at the docs but it doesn't mention it.

Upvotes: 1

Views: 4819

Answers (2)

Michael Yuwono
Michael Yuwono

Reputation: 2617

Use ModalRoute.of(context).settings.arguments

Inside your build method of the /secondRoute:

final args = ModalRoute.of(context).settings.arguments as Map<String, String>;
final arg1 = args["key"];

Upvotes: 8

Andrii Turkovskyi
Andrii Turkovskyi

Reputation: 29458

Create class for arguments:

class ScreenArguments {
  final String title;
  final String message;

  ScreenArguments(this.title, this.message);
}

And extract them inside widget:

class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';

  @override
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute settings and cast
    // them as ScreenArguments.
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}

And for sending params:

Navigator.pushNamed(
  context,
  ExtractArgumentsScreen.routeName,
  arguments: ScreenArguments(
    'Extract Arguments Screen',
    'This message is extracted in the build method.',
  ),
);

Upvotes: 4

Related Questions