I am writing widget tests in Flutter. I am not able to find any documentation to execute "Go Back to Prevoius Screen" as I do not find any method for that. Please help with some sample "test" code for the same.
Asked
Active
Viewed 4,859 times
6
-
1https://docs.flutter.io/flutter/flutter_test/WidgetTester/pageBack.html – Günter Zöchbauer Aug 31 '18 at 04:13
-
Thank you for quick response. Any sample code to refer? – STeamup Aug 31 '18 at 04:47
-
@GünterZöchbauer This test whether there is a button, but not if the route was actually popped. – creativecreatorormaybenot Aug 31 '18 at 07:35
-
https://stackoverflow.com/questions/50704647/how-to-test-navigation-via-navigator-in-flutter – Günter Zöchbauer Aug 31 '18 at 07:48
-
2I used *tester.pumpAndSettle() * after entering into page then tried tester.goBack() and it worked. Thank you @Günter Zöchbauer – STeamup Sep 07 '18 at 03:21
-
Glad to hear. You could answer your own question with your solution. – Günter Zöchbauer Sep 07 '18 at 03:59
-
@GünterZöchbauer when I use tester.pageBack() , I get an error zero widgets with type "CupertinoNavigationBarBackButton" (this is in widget test) `phonePage = MediaQuery( data: MediaQueryData(), child: MaterialApp( home: PhonePage(), navigatorObservers: [observer], ), );` – TSR Jun 03 '20 at 00:16
-
@TSR I face the same error. Did you solve it? – Bassam Jan 28 '21 at 03:11
1 Answers
1
You have to mock navigation observer.
First create class
class MockNavigatorObserver extends Mock implements NavigatorObserver
Declare
final mockObserver = MockNavigatorObserver();
in your test file.Put your widget inside
MaterialApp
and add propertynavigatorObservers: [mockObserver],
Finally inside your testWidgets block {} mock like this:
final mockObserver = MockNavigatorObserver(); final backIcon = find.byIcon(Icons.arrow_back_ios); expect(backIcon, findsOneWidget); await tester.tap(backIcon); verify(mockObserver.didPop(any, any)); await tester.pumpAndSettle();

Quyen Anh Nguyen
- 1,204
- 13
- 21