'Argument not being passed to screen
In main.dart created such routes:
routes: {
'/home': (context) => HomeScreenWidget(),
'/color_picker': (context) => ColorPickerWidget(),
TextValueScreen.routeName: (context) =>
const TextValueScreen(color: '',),
},
initialRoute: '/home',
I'm trying to pass an argument "color" to the following screen:
// default value of select
String selectedValue = "Yellow";
// next step route
void _changeColor(String color) {
Navigator.pushNamed(
context,
TextValueScreen.routeName,
arguments: {color: color}
);
}
ElevatedButton(onPressed: () => _changeColor(selectedValue),
child: const Text('Next'),
),
But the argument is not passed. How can this problem be solved?
Solution 1:[1]
This is how to access arguments on a target route:
final args = ModalRoute.of(context)!.settings.arguments
Solution 2:[2]
Navigate and pass the Color argument like this
Navigator.pushNamed(
context,
TextValueScreen.routeName,
arguments: Colors.yellow
//you can pass any color you want
);
Access the Navigation inside your TextValueScreen
@override
Widget build(BuildContext context) {
var colorArg = ModalRoute.of(context)!.settings.arguments as Color;
return yourWidget();
}
For this to work the argument needs to be a Color obejct. If you want to pass another kind of object just specify what you are giving as a navigation parameter inside your build method
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user18309290 |
| Solution 2 |
