简体   繁体   English

将数据传递给 Flutter 中的小部件

[英]Passing data to widgets in Flutter

Do I understand correctly that in Flutter state fields are analogous to state in React (that is, is controlled by an element itself) and widget fields are analogous to props in React (that is, are received from the parent)?我是否正确理解在 Flutter state 字段类似于 React 中的 state (即由元素本身控制)和小部件字段类似于 React 中的父项(是,)?

Example:例子:

// Called as `PlacesAdd(db: db, coord: coord)`.
class PlacesAdd extends StatefulWidget {
  Database? db;
  LatLng? coord;

  PlacesAdd({super.key, required this.db, required this.coord});

  @override
  State<PlacesAdd> createState() => _PlacesAddState();
}

class _PlacesAddState extends State<PlacesAdd> {
  void Function() onChoosePlace(_PlaceData place) {
    return () => {
      widget.db.insert(/*...*/)
          .then((c) => {});
    };
  }

  @override
  Widget build(BuildContext context) {
    /*...*/
  }
}

Or should it be duplicated in the state?:还是应该在 state 中复制它?:

  Database db?;

  @override
  Widget build(BuildContext context) {
    setState(() => {
      db = widget.db;
    });

If it is the case, then should I then use in the PlacesAddState the field db of the state or directly widget.db ?如果是这种情况,那么我应该在 PlacesAddState 中使用PlacesAddState的字段db还是直接widget.db

If you have to change the value of a field, I recommend to make a 'duplicate'.如果您必须更改字段的值,我建议进行“复制”。

Only if you are using final fields you don't have to change anymore like a color passed to your widget as a param I would use the value from the parent widget.仅当您使用最终字段时,您不必再更改像传递给小部件的颜色作为参数,我会使用父小部件中的值。

In the official docs , they do it the same way:在官方文档中,他们这样做的方式相同:

class Bird extends StatefulWidget {
  const Bird({
    super.key,
    this.color = const Color(0xFFFFE306),
    this.child,
  });

  final Color color;
  final Widget? child;

  @override
  State<Bird> createState() => _BirdState();
}

class _BirdState extends State<Bird> {
  double _size = 1.0;

  void grow() {
    setState(() { _size += 0.1; });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.color,
      transform: Matrix4.diagonal3Values(_size, _size, 1.0),
      child: widget.child,
    );
  }
}

They could also have defined the double size in the parent widget.他们也可以在父窗口小部件中定义双倍尺寸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM