【问题标题】:How do you pass/bind a value through a RaisedButton in Flutter?如何通过 Flutter 中的 RaisedButton 传递/绑定值?
【发布时间】:2018-03-14 02:22:58
【问题描述】:

我有一个 RaisedButtons 的 ListView,其中每个 RaisedButton 看起来像这样。每个 RaisedButton 的 name 变量都不同:

  new RaisedButton(
      onPressed: _navigateToRoute,
      child: new Text(name),
  ),

点击 RaisedButton 调用 _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'),
        );
      },
    ));
  }

当点击特定的 RaisedButton(例如,假设我们点击 ListView 中的第一个 RaisedButton,name = 'Hello'),我想将 name 变量传递给新路由。我怎么做?有没有办法将name 存储在context 变量中?我应该使用另一个小部件而不是 RaisedButton 吗?

我可以使用Named Navigator Route,但我不想为我的 ListView 中的每个项目硬编码路线。

我找到了this Github issue,但我不确定它是否与我遇到的相同。

【问题讨论】:

    标签: listview button parameters parameter-passing flutter


    【解决方案1】:

    您可以将名称作为输入传递给 onPressed 函数。 IE。

      new RaisedButton(
          onPressed: () => _navigateToRoute(name),
          child: new Text(name),
      ),
    

    函数签名将是:

      void _navigateToRoute(String name)
    

    【讨论】:

    • 我想强调() =&gt; 部分是必不可少的。否则,您的方法将在构建期间立即被调用。
    【解决方案2】:

    您可以将任何变量传递给方法:

    new RaisedButton(
      onPressed: () => _navigateToRoute(name),
      child: new Text(name),
    ),
    

    只要你定义你的方法能够接收变量。比你可以用那个变量做任何你想做的事情。

    void _navigateToRoute(String name) {
      Navigator.of(context).push(new MaterialPageRoute<Null>(
        builder: (BuildContext context) {
          return new Scaffold(
            body: new Text(name),
          );
        },
      ));
    }
    

    你甚至可以在你的类层次结构中进一步向下传递:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多