In this part of the series I want to show you how to use the previously described page routing to pass information to the new page.
This is Part 2 of 4 of my Series: 🦋Flutter - Next Level Navigation. If you haven’t read the first part of the series yet, I recommend you to do so.
content
Passing Information
To get straight to the point. Passing information as the next step is not difficult, but it can easily lead to errors. Therefore it is especially important to do error handling. But in order to pass information, the following 2 steps must be done first:
1. pass arguments
To pass arguments when calling the
Navigator
object, the
arguments
parameter must be filled with data of any kind.
Navigator.of(context)
.pushNamed('/page2', arguments: myArguments)
These can be primitive data types, like integers or strings, or complex objects. If you want to pass several single items of data, it is recommended to put them in a list.
2. process arguments
In the
RouteGenerator
class previously created, the passed arguments can now be extracted and passed to the new page. This can be done as following:
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case '/page2':
return MaterialPageRoute(
builder: (_) =>
IntroductionView(arguments: args));
}
}
Prevent runtime errors
To avoid runtime errors, it is important to check whether the arguments entered are valid. This can be achieved for example by checking the type. For instance, if only passed integer values are allowed, this can be done as shown below:
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case '/page2':
if (args is int) {
return MaterialPageRoute(
builder: (_) =>
IntroductionView(arguments: args));
}
}
}
If the passed argument is not valid, null is passed to the navigator and the new page does not appear. This is better than an error message, but not very helpful for the user. If you want to know how to create an error page check out the 3rd post in this series. Follow me to not miss the following posts of this series