3

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

Tree
  • 29,135
  • 24
  • 78
  • 98

3 Answers3

1

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 
  });
}

AKR
  • 11
  • 1
1

This worked for me and is relatively simple.

var widget = StatelessWidgetExample();

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

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();
  }
}
Tree
  • 29,135
  • 24
  • 78
  • 98
  • Thanks for answer and can you help me with dropdown design [How to customize Dropdown Button and items in flutter?][https://stackoverflow.com/questions/71021122/how-to-customize-dropdown-button-and-items-in-flutter] – shanmkha Feb 07 '22 at 15:38