I have a StatefulWidget (call it MyWidget
) whose State (MyWidgetState
) has a field myData
which is initialized during initState()
as follows:
void initState() {
super.initState();
myData = new myData(config.someField.getId());
}
When the user presses a button, myData is added to or removed from a global list.
I'm trying to write a unit test to test this behavior but I don't know how to get access to a MyWidgetState. I tried including this in the setup():
widget = MyWidget();
widgetState = widget.createState();
widgetState.init();
but it crashes every time when it tries to initState(), complaining that "someField was called on null". That's fine. I was probably cheating by trying to do it that way and I ought to do something with a WidgetBuilder or launch an application using MyWidget and then find MyWidget in the tree once it's properly instantiated.
If I do all of that, once I do how can I access that MyWidget's MyWidgetState to get a copy of myData and compare it to the global list?
You can create a state and then access it's content. Following Ian Hickson answer. hereunder is an example for the implementation:
final MyWidgetState myWidgetState = tester.state(find.byType(MyWidget));
Then you can access the state content:
myWidgetState.myData;
You can find more examples in the Flutter's repo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With