Best way to transfer data between widgets in Flutter

I am developing my own widget, which is used in a different view. In this custom widget, I have one class property that stores information, say that it is a list that receives new elements inside the widget. Now I want to get items from this list from the level of my main widget.

How to do it? I don't want to create such a variable: var customWidget = MyCustomWidget()and then get the internal variable as customWidget.createState().myList- I think this is a terrible solution (and I'm not sure if this will work). Also, passing the list to the constructor of my custom widget looks very ugly.

Is there any other way to get a different state of widgets?

UPDATE:

I have already found a good solution. First we need to define a key:

final key = new GlobalKey<MyCustomWidgetState>();

Then we need to put it in our custom widget when creating:

new MyCustomView(key: key);

and add this parameter to MyCustomWidget:

MyCustomWidget({Key key}) : super(key: key);

Now we have access to the data in the custom widget with: key.currentState

+4
source share
1 answer

Also, passing the list to the constructor of my custom widget looks very ugly.

This is the right decision. Although you can solve this problem using other tools (GlobalKey), they are out of date.

A widget requesting another widget state to change it is anti-patern .

Intead, you should find a way to pass data down. In most cases, a constructor is the right way to achieve this. But you can also use BuildContext contextyour widget to access data from this parent. For instance:

  • context.inheritWidgetOfExactType<Type>(); InheritedWidget
  • context.ancestorStateOfType(typeMatcher); StatefulWidget ( , -).
0

Source: https://habr.com/ru/post/1693931/


All Articles