Flutter - 自定义小部件 - 如何从中获取值

Bri*_* Oh 4 widget flutter

这是我遇到的问题的一个简单示例。给定以下示例,如何从类外部获取“counter”的值?

class Counter extends StatefulWidget {
  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int counter = 0;
  void increaseCount() {
    setState(() => this.counter++);
    print("New count = $counter");
  }

  Widget build(context) {
    return new RaisedButton(
      onPressed: increaseCount,
      child: new Text('Tap To Add'),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Hos*_*sar 7

在 Flutter 中你通常做的是传递一个回调函数,在那个函数中你可以传递你需要的值,例如

class Counter extends StatefulWidget {
  // you can use a callback function
  final ValueSetter<int> callback;

  Counter({this.callback});

  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int counter = 0;
  void increaseCount() {
    setState(() => this.counter++);
    print("New count = $counter");
    // Here you can pass the value
    widget.callback(this.counter);
  }

  Widget build(context) {
    return new RaisedButton(
      onPressed: increaseCount,
      child: new Text('Tap To Add'),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在调用您的小部件时,您可以执行以下操作:

Counter(callback: (counter){
      // Here you can take some actions on counter
    });
Run Code Online (Sandbox Code Playgroud)

这是我所知道的最简单的方法,或者您可以使用其他一些模式,例如 bloc 或其他模式。
希望这有帮助。