Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)?

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?:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading