First, bear in mind that in Flutter data can only be passed downward. It is by design not possible to access data of children, only parents (although there are some hacks around it).
From this point, there are 2 main solutions to pass data:
- Add the wanted data to your widgets constructors.
I don't think there is much to say here. Easy to use. But boring when you want to pass one field to all your widget tree. Use this method only when the scope of a value is limited. If it's something like configurations or user details, go for the second solution.
class Bar extends StatelessWidget {
final String data;
Bar({this.data});
@override
Widget build(BuildContext context) {
return Text(data);
}
}
- Using Flutter's
BuildContext
Each widget has access to a BuildContext
. This class allows one widget to fetch information from any of their ancestors using one of the following methods:
As a matter of facts, if there's a data that needs to be accessed many times, prefer inheritFromWidgetOfExactType
.
This uses InheritedWidget
; which are specifics kind of widgets that are extremely fast to access to.
See Flutter: How to correctly use an Inherited Widget? for more details on their usage
As a side note, there a third solution. Which is GlobalKey
I won't go into too many details, as this is more a hack than a proper solution. (see Builder versus GlobalKey)
But basically, it allows getting the state/context of any widgets outside of the build
call. Be it parents or children.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…