will_pop_test.dart 14.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
6
import 'package:flutter_test/flutter_test.dart';
7
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
8 9 10 11

bool willPopValue = false;

class SamplePage extends StatefulWidget {
12
  const SamplePage({ super.key });
13
  @override
14
  SamplePageState createState() => SamplePageState();
15 16 17
}

class SamplePageState extends State<SamplePage> {
18
  ModalRoute<void>? _route;
19 20 21

  Future<bool> _callback() async => willPopValue;

22
  @override
23 24
  void didChangeDependencies() {
    super.didChangeDependencies();
25 26 27 28 29 30 31 32 33
    _route?.removeScopedWillPopCallback(_callback);
    _route = ModalRoute.of(context);
    _route?.addScopedWillPopCallback(_callback);
  }

  @override
  void dispose() {
    super.dispose();
    _route?.removeScopedWillPopCallback(_callback);
34 35 36 37
  }

  @override
  Widget build(BuildContext context) {
38 39
    return Scaffold(
      appBar: AppBar(title: const Text('Sample Page')),
40 41 42 43 44 45 46
    );
  }
}

int willPopCount = 0;

class SampleForm extends StatelessWidget {
47
  const SampleForm({ super.key, required this.callback });
48 49 50 51 52

  final WillPopCallback callback;

  @override
  Widget build(BuildContext context) {
53 54 55 56
    return Scaffold(
      appBar: AppBar(title: const Text('Sample Form')),
      body: SizedBox.expand(
        child: Form(
57 58 59 60
          onWillPop: () {
            willPopCount += 1;
            return callback();
          },
61
          child: const TextField(),
62 63 64 65 66 67
        ),
      ),
    );
  }
}

68
// Expose the protected hasScopedWillPopCallback getter
69 70
class _TestPageRoute<T> extends MaterialPageRoute<T> {
  _TestPageRoute({
71 72 73
    super.settings,
    required super.builder,
  }) : super(maintainState: true);
74 75 76 77

  bool get hasCallback => super.hasScopedWillPopCallback;
}

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
class _TestPage extends Page<dynamic> {
  _TestPage({
    required this.builder,
    required LocalKey key,
  })  : _key = GlobalKey(),
        super(key: key);

  final WidgetBuilder builder;
  final GlobalKey<dynamic> _key;

  @override
  Route<dynamic> createRoute(BuildContext context) {
    return _TestPageRoute<dynamic>(
        settings: this,
        builder: (BuildContext context) {
          // keep state during move to another location in tree
          return KeyedSubtree(key: _key, child: builder.call(context));
        });
  }
}
98

99
void main() {
100
  testWidgetsWithLeakTracking('ModalRoute scopedWillPopupCallback can inhibit back button', (WidgetTester tester) async {
101
    await tester.pumpWidget(
102 103 104 105
      MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
106
            builder: (BuildContext context) {
107
              return Center(
108
                child: TextButton(
109
                  child: const Text('X'),
110
                  onPressed: () {
111
                    showDialog<void>(
112
                      context: context,
113
                      builder: (BuildContext context) => const SamplePage(),
114 115 116 117 118 119 120 121 122 123
                    );
                  },
                ),
              );
            },
          ),
        ),
      ),
    );

124 125 126
    expect(find.byTooltip('Back'), findsNothing);
    expect(find.text('Sample Page'), findsNothing);

127 128 129 130 131 132 133 134 135 136 137 138 139
    await tester.tap(find.text('X'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));

    expect(find.text('Sample Page'), findsOneWidget);

    willPopValue = false;
    await tester.tap(find.byTooltip('Back'));
    await tester.pump();
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));
    expect(find.text('Sample Page'), findsOneWidget);

140
    // Use didPopRoute() to simulate the system back button. Check that
141
    // didPopRoute() indicates that the notification was handled.
142
    final dynamic widgetsAppState = tester.state(find.byType(WidgetsApp));
143
    // ignore: avoid_dynamic_calls
144 145 146
    expect(await widgetsAppState.didPopRoute(), isTrue);
    expect(find.text('Sample Page'), findsOneWidget);

147 148 149 150 151 152 153 154
    willPopValue = true;
    await tester.tap(find.byTooltip('Back'));
    await tester.pump();
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));
    expect(find.text('Sample Page'), findsNothing);
  });

155
  testWidgetsWithLeakTracking('willPop will only pop if the callback returns true', (WidgetTester tester) async {
156 157 158 159 160 161 162
    Widget buildFrame() {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
            builder: (BuildContext context) {
              return Center(
163
                child: TextButton(
164 165
                  child: const Text('X'),
                  onPressed: () {
166
                    Navigator.of(context).push(MaterialPageRoute<void>(
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                      builder: (BuildContext context) {
                        return SampleForm(
                          callback: () => Future<bool>.value(willPopValue),
                        );
                      },
                    ));
                  },
                ),
              );
            },
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame());
    await tester.tap(find.text('X'));
    await tester.pumpAndSettle();
    expect(find.text('Sample Form'), findsOneWidget);

    // Should pop if callback returns true
    willPopValue = true;
    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();
    expect(find.text('Sample Form'), findsNothing);
  });

194
  testWidgetsWithLeakTracking('Form.willPop can inhibit back button', (WidgetTester tester) async {
195
    Widget buildFrame() {
196 197 198 199
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
200
            builder: (BuildContext context) {
201
              return Center(
202
                child: TextButton(
203
                  child: const Text('X'),
204
                  onPressed: () {
205
                    Navigator.of(context).push(MaterialPageRoute<void>(
206
                      builder: (BuildContext context) {
207 208
                        return SampleForm(
                          callback: () => Future<bool>.value(willPopValue),
209
                        );
210
                      },
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
                    ));
                  },
                ),
              );
            },
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame());

    await tester.tap(find.text('X'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));

    expect(find.text('Sample Form'), findsOneWidget);

    willPopValue = false;
    willPopCount = 0;
    await tester.tap(find.byTooltip('Back'));
    await tester.pump(); // Start the pop "back" operation.
    await tester.pump(); // Complete the willPop() Future.
    await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
    expect(find.text('Sample Form'), findsOneWidget);
    expect(willPopCount, 1);

    willPopValue = true;
    willPopCount = 0;
    await tester.tap(find.byTooltip('Back'));
    await tester.pump(); // Start the pop "back" operation.
    await tester.pump(); // Complete the willPop() Future.
    await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
    expect(find.text('Sample Form'), findsNothing);
    expect(willPopCount, 1);
  });

248
  testWidgetsWithLeakTracking('Form.willPop callbacks do not accumulate', (WidgetTester tester) async {
249 250
    Future<bool> showYesNoAlert(BuildContext context) async {
      return (await showDialog<bool>(
251
        context: context,
252
        builder: (BuildContext context) {
253
          return AlertDialog(
254
            actions: <Widget> [
255
              TextButton(
256
                child: const Text('YES'),
257
                onPressed: () { Navigator.of(context).pop(true); },
258
              ),
259
              TextButton(
260
                child: const Text('NO'),
261
                onPressed: () { Navigator.of(context).pop(false); },
262 263 264 265
              ),
            ],
          );
        },
266
      ))!;
267 268 269
    }

    Widget buildFrame() {
270 271 272 273
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
274
            builder: (BuildContext context) {
275
              return Center(
276
                child: TextButton(
277
                  child: const Text('X'),
278
                  onPressed: () {
279
                    Navigator.of(context).push(MaterialPageRoute<void>(
280
                      builder: (BuildContext context) {
281
                        return SampleForm(
282 283
                          callback: () => showYesNoAlert(context),
                        );
284
                      },
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
                    ));
                  },
                ),
              );
            },
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame());

    await tester.tap(find.text('X'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));

    expect(find.text('Sample Form'), findsOneWidget);

    // Press the Scaffold's back button. This causes the willPop callback
    // to run, which shows the YES/NO Alert Dialog. Veto the back operation
    // by pressing the Alert's NO button.
    await tester.tap(find.byTooltip('Back'));
    await tester.pump(); // Start the pop "back" operation.
    await tester.pump(); // Call willPop which will show an Alert.
    await tester.tap(find.text('NO'));
    await tester.pump(); // Start the dismiss animation.
    await tester.pump(); // Resolve the willPop callback.
    await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
    expect(find.text('Sample Form'), findsOneWidget);

Ian Hickson's avatar
Ian Hickson committed
315 316 317 318
    // Do it again.
    // Each time the Alert is shown and dismissed the FormState's
    // didChangeDependencies() method runs. We're making sure that the
    // didChangeDependencies() method doesn't add an extra willPop callback.
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    await tester.tap(find.byTooltip('Back'));
    await tester.pump(); // Start the pop "back" operation.
    await tester.pump(); // Call willPop which will show an Alert.
    await tester.tap(find.text('NO'));
    await tester.pump(); // Start the dismiss animation.
    await tester.pump(); // Resolve the willPop callback.
    await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
    expect(find.text('Sample Form'), findsOneWidget);

    // This time really dismiss the SampleForm by pressing the Alert's
    // YES button.
    await tester.tap(find.byTooltip('Back'));
    await tester.pump(); // Start the pop "back" operation.
    await tester.pump(); // Call willPop which will show an Alert.
    await tester.tap(find.text('YES'));
    await tester.pump(); // Start the dismiss animation.
    await tester.pump(); // Resolve the willPop callback.
    await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
    expect(find.text('Sample Form'), findsNothing);
  });

340
  testWidgetsWithLeakTracking('Route.scopedWillPop callbacks do not accumulate', (WidgetTester tester) async {
341
    late StateSetter contentsSetState; // call this to rebuild the route's SampleForm contents
342 343
    bool contentsEmpty = false; // when true, don't include the SampleForm in the route

344
    final _TestPageRoute<void> route = _TestPageRoute<void>(
345
      builder: (BuildContext context) {
346
        return StatefulBuilder(
347 348
          builder: (BuildContext context, StateSetter setState) {
            contentsSetState = setState;
349
            return contentsEmpty ? Container() : SampleForm(key: UniqueKey(), callback: () async => false);
350
          },
351 352 353 354 355
        );
      },
    );

    Widget buildFrame() {
356 357 358 359
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
360
            builder: (BuildContext context) {
361
              return Center(
362
                child: TextButton(
363
                  child: const Text('X'),
364
                  onPressed: () {
365
                    Navigator.of(context).push(route);
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
                  },
                ),
              );
            },
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame());

    await tester.tap(find.text('X'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));

    expect(find.text('Sample Form'), findsOneWidget);
    expect(route.hasCallback, isTrue);

    // Rebuild the route's SampleForm child an additional 3x for good measure.
    contentsSetState(() { });
    await tester.pump();
    contentsSetState(() { });
    await tester.pump();
    contentsSetState(() { });
    await tester.pump();

    // Now build the route's contents without the sample form.
    contentsEmpty = true;
    contentsSetState(() { });
    await tester.pump();

    expect(route.hasCallback, isFalse);
  });
399

400
  testWidgetsWithLeakTracking('should handle new route if page moved from one navigator to another', (WidgetTester tester) async {
401 402 403 404 405 406 407 408 409 410 411 412 413
    // Regression test for https://github.com/flutter/flutter/issues/89133
    late StateSetter contentsSetState;
    bool moveToAnotherNavigator = false;

    final List<Page<dynamic>> pages = <Page<dynamic>>[
      _TestPage(
        key: UniqueKey(),
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: () async => true,
            child: const Text('anchor'),
          );
        },
414
      ),
415 416
    ];

417
    Widget buildNavigator(Key? key, List<Page<dynamic>> pages) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
      return Navigator(
        key: key,
        pages: pages,
        onPopPage: (Route<dynamic> route, dynamic result) {
          return route.didPop(result);
        },
      );
    }

    Widget buildFrame() {
      return MaterialApp(
        home: Scaffold(
          body: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              contentsSetState = setState;
              if (moveToAnotherNavigator) {
434
                return buildNavigator(const ValueKey<int>(1), pages);
435
              }
436
              return buildNavigator(const ValueKey<int>(2), pages);
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
            },
          ),
        ),
      );
    }

    await tester.pumpWidget(buildFrame());
    await tester.pump();
    final _TestPageRoute<dynamic> route1 = ModalRoute.of(tester.element(find.text('anchor')))! as _TestPageRoute<dynamic>;
    expect(route1.hasCallback, isTrue);
    moveToAnotherNavigator = true;
    contentsSetState(() {});

    await tester.pump();
    final _TestPageRoute<dynamic> route2 = ModalRoute.of(tester.element(find.text('anchor')))! as _TestPageRoute<dynamic>;

    expect(route1.hasCallback, isFalse);
    expect(route2.hasCallback, isTrue);
  });
456
}