Flutter testing WillPopScope with back button

Viewed 1292

On my Home widget, when user taps system back button, It shows by a WillPopScope a confirmation dialog widget. I want to test this dialog but I cant figure it out how to press the back button on a test file.

3 Answers

I had the same problem but i had no back button in my app. I wanted to test the android system back button. This is how I did it. Maybe it's helpful for people who run into the same problem as me.

testWidgets("test onWillPop",(WidgetTester tester) async {
    bool willPopCalled = false;
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: WillPopScope(
            onWillPop: () async {
              willPopCalled = true;
              return false;
            },
            child: Container(),
          ),
        ),
      ),
    );

    final dynamic widgetsAppState = tester.state(find.byType(WidgetsApp));
    await widgetsAppState.didPopRoute();
    await tester.pump();

    expect(willPopCalled, true);
});

Inspired by: https://github.com/flutter/flutter/blob/master/packages/flutter/test/material/will_pop_test.dart

I cant figure it out how to press the back button on a test file.

This will help you to see back button on appbar(top part of app). It will allow you to see back button via appbar

return WillPopScope(
  onWillPop: _onWillPop,
  child: Scaffold(
    appBar: AppBar(
      title: Text("Title"),
      centerTitle: true,
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.black),
        onPressed: () => _onWillPop(),
      ),
    ),
    body: Body(),
  ),
);

_onWillPop will be your "confirmation dialog widget" for your question.

Apparently, you cannot access Navigator in the test. So my solution is to include BackButton somewhere in the pumped widget and to pop the page like this:

await tester.pumpWidget(MaterialApp(
  home: Scaffold(
    body: Container(
      child: BackButton(),
    ),
  ),
));

...

await tester.pageBack();
Related