Lucas Pires
Lucas Pires

Reputation: 113

Flutter testing WillPopScope with back button

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.

Upvotes: 11

Views: 3465

Answers (4)

Matt Booth
Matt Booth

Reputation: 2053

The following worked for me, because I wanted to kill 2 birds with 1 stone, and actually ensure the back button (which is generated by default in the AppBar, not added by me) was appearing too;

final backButton = find.byTooltip('Back');
await tester.tap(backButton);

Then obviously just pumpAndSettle, and test your other screen.

Upvotes: 0

Stan
Stan

Reputation: 668

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

Upvotes: 6

Jindra Žák
Jindra Žák

Reputation: 88

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

Upvotes: 2

BlackySen
BlackySen

Reputation: 45

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.

Upvotes: 1

Related Questions