How to simulate disposing widget in flutter test?

Viewed 497

This method will call the init function inside the stateless widget. But how to emulate the call to dispose function?

    var widget = StatelessWidgetExample();
    await tester.pumpWidget(widget);

I also tried to emulate the removal from the tree.

    await tester.pumpWidget(widget);
    await tester.pumpWidget(Container());

but it didn't work

2 Answers

Did it like this


    var key2 = Key('a');
    var testStateful = _TestStateful(
      key: key2,
      child: TestInitDispose(),
    );

    await tester.pumpWidget(testStateful);
    /// will call init

    var state = tester.firstState<__TestStatefulState>(find.byKey(key2));
    state.remove();

    await tester.pump();
    /// will call dispose
  });

...

class _TestStateful extends StatefulWidget {
  final Widget child;
  const _TestStateful({Key? key, required this.child}) : super(key: key);

  @override
  __TestStatefulState createState() => __TestStatefulState();
}

class __TestStatefulState extends State<_TestStateful> {
  bool showChild = true;
  void remove() {
    setState(() {
      showChild = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return showChild ? widget.child : Container();
  }
}

You could use a StreamBuilder and replace YourWidget with another widget, then the dispose method for YourWidget is called.

void main() {
  late StreamController<Widget> widgetStreamController;

  setUp(() async {
    widgetStreamController = StreamController<Widget>();
  });

  tearDown(() async {
    await widgetStreamController.close();
  });

  Widget buildApp() {
    return MaterialApp(
      home: StreamBuilder<Widget>(
        stream: widgetStreamController.stream,
        builder: (context, snapshot) {
          return snapshot.data ?? Container();
        },
      ),
    );
  }

  testWidgets('dispose widget', (tester) async {
    await tester.pumpWidget(buildApp());
    await tester.pumpAndSettle();

    widgetStreamController.add(YourWidget());
    await tester.pumpAndSettle();

    // todo: check here if YourWidget is displayed

    widgetStreamController.add(AnotherWidget());
    await tester.pumpAndSettle();

    // todo: check here if dispose was called 
  });
}

Related