Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the contents of a StatefulWidget's State during a unit test?

Tags:

flutter

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?

like image 961
Reagankm Avatar asked Feb 09 '17 03:02

Reagankm


1 Answers

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.

like image 109
user2181452 Avatar answered Sep 25 '22 02:09

user2181452