如何在 Dart/Flutter 中从其自己的回调 (onPressed) 中访问 Widget

wzr*_*337 6 dart flutter

我有以下代码:

  @override
  Widget build(BuildContext context) {
    return new Container(
      height: 72.0, // in logical pixels
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
      decoration: new BoxDecoration(color: Colors.white),
      // Row is a horizontal, linear layout.
      child: new MaterialButton(
        child: new Text(
          _sprinkler.name,
          style: new TextStyle(color: Colors.white)
          ),
        splashColor: Colors.blueAccent,
        color: Colors.blue[800],
        onPressed: () {
          print("onTap(): tapped" + _sprinkler.name);
        },
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

onPressed(),我想更改 Buttons 样式 - 代表洒水器活动。

因此,我需要访问 MaterialButton Widget 本身。

但是如何从回调中访问它?

非常感谢,对于 n00b 的问题,我很抱歉,我是 Dart 和 Flutter 的新手;)

wzr*_*337 2

感谢您的意见。正确的解决方案实际上是您推荐的,如下所示:

class SprinklerListItem extends StatefulWidget {
  // This class is the configuration for the state. It holds the
  // values (in this nothing) provided by the parent and used by the build
  // method of the State. Fields in a Widget subclass are always marked "final".
  final Sprinkler _sprinkler;
  SprinklerListItem(this._sprinkler);


  @override
  _SprinklerListItemState createState() {
    return new _SprinklerListItemState(this._sprinkler);
  }
}


class _SprinklerListItemState extends State<SprinklerListItem> {
  final Sprinkler _sprinkler;

  _SprinklerListItemState(this._sprinkler);

  Color textColor = Colors.white;
  Color bgColor = Colors.blue[800];
  @override
  Widget build(BuildContext context) {
    return new Container(
      height: 72.0, // in logical pixels
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
      decoration: new BoxDecoration(color: Colors.white),
      // Row is a horizontal, linear layout.
      child: new MaterialButton(
        child: new Text(
          _sprinkler.name,
          style: new TextStyle(color: textColor)
          ),
        splashColor: Colors.blueAccent,
        color: bgColor,
        onPressed: () {
          this.setState(() {
            textColor = Colors.grey;
            bgColor = Colors.red;
          });
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)