How do you pass/bind a value through a RaisedButton in Flutter?


Asked by Mary on October 02, 2017 (source).

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.


Question answered by Mary (source).

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)