I have a ListView of RaisedButtons, where each RaisedButton looks like this. The name
variable is different for each RaisedButton:
new RaisedButton(
onPressed: _navigateToRoute,
child: new Text(name),
),
Tapping on a RaisedButton calls _navigateToRoute():
void _navigateToRoute() {
Navigator.of(context).push(new MaterialPageRoute<Null>(
builder: (BuildContext context) {
return new Scaffold(
body: new Text('A value with the word "Hello" should go here'),
);
},
));
}
When a specific RaisedButton is tapped (e.g. let's say we tap the first RaisedButton in the ListView, where name = 'Hello'
), I would like to pass the name
variable to the new route. How do I do that? Is there a way to store name
in the context
variable? Should I use another widget instead of RaisedButton?
I could use a Named Navigator Route but I don't want to hardcode a route for each item in my ListView.
I found this Github issue, and I'm not sure if it's the same thing I'm encountering.
Create RaisedButton and wrap it with Center widget. Give the child of RaisedButton as a Text widget. Perform onPressed function when the button is tapped. Perform optional onLongPress function when button is long pressed.
How do you send a function as a parameter in Flutter? Step 1: Define a Dart method that takes a function parameter. Step 2: Create one or more functions to pass into that function parameter. Step 3: Pass the functions into the method.
You can pass the name as an input to the onPressed function. I.e.
new RaisedButton(
onPressed: () => _navigateToRoute(name),
child: new Text(name),
),
The function signature would then be:
void _navigateToRoute(String name)
You can just pass any variable to a method:
new RaisedButton(
onPressed: () => _navigateToRoute(name),
child: new Text(name),
),
As long as you define your method to be able to receive variable. Than you can do what ever you want with that variable.
void _navigateToRoute(String name) {
Navigator.of(context).push(new MaterialPageRoute<Null>(
builder: (BuildContext context) {
return new Scaffold(
body: new Text(name),
);
},
));
}
You could even pass it further down in your class hierarchy:
void _navigateToRoute(String name) {
Navigator.of(context).push(new MaterialPageRoute<Null>(
builder: (BuildContext context) {
return new MyNewPage(name);
},
));
}
class MyNewPage extends StatelessWidget {
String name;
MyNewPage(this.name);
...rest of the widget code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With