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

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';

bool willPopValue = false;

class SamplePage extends StatefulWidget {
11
  const SamplePage({ Key? key }) : super(key: key);
12
  @override
13
  SamplePageState createState() => SamplePageState();
14 15 16
}

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

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

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

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

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

int willPopCount = 0;

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

  final WillPopCallback callback;

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

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

  bool get hasCallback => super.hasScopedWillPopCallback;
}


76 77 78
void main() {
  testWidgets('ModalRoute scopedWillPopupCallback can inhibit back button', (WidgetTester tester) async {
    await tester.pumpWidget(
79 80 81 82
      MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
83
            builder: (BuildContext context) {
84
              return Center(
85
                child: TextButton(
86
                  child: const Text('X'),
87
                  onPressed: () {
88
                    showDialog<void>(
89
                      context: context,
90
                      builder: (BuildContext context) => const SamplePage(),
91 92 93 94 95 96 97 98 99 100
                    );
                  },
                ),
              );
            },
          ),
        ),
      ),
    );

101 102 103
    expect(find.byTooltip('Back'), findsNothing);
    expect(find.text('Sample Page'), findsNothing);

104 105 106 107 108 109 110 111 112 113 114 115 116
    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);

117
    // Use didPopRoute() to simulate the system back button. Check that
118
    // didPopRoute() indicates that the notification was handled.
119
    final dynamic widgetsAppState = tester.state(find.byType(WidgetsApp)); // ignore: unnecessary_nullable_for_final_variable_declarations
120 121 122
    expect(await widgetsAppState.didPopRoute(), isTrue);
    expect(find.text('Sample Page'), findsOneWidget);

123 124 125 126 127 128 129 130
    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);
  });

131 132 133 134 135 136 137 138
  testWidgets('willPop will only pop if the callback returns true', (WidgetTester tester) async {
    Widget buildFrame() {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
            builder: (BuildContext context) {
              return Center(
139
                child: TextButton(
140 141
                  child: const Text('X'),
                  onPressed: () {
142
                    Navigator.of(context).push(MaterialPageRoute<void>(
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
                      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);
  });

170 171
  testWidgets('Form.willPop can inhibit back button', (WidgetTester tester) async {
    Widget buildFrame() {
172 173 174 175
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
176
            builder: (BuildContext context) {
177
              return Center(
178
                child: TextButton(
179
                  child: const Text('X'),
180
                  onPressed: () {
181
                    Navigator.of(context).push(MaterialPageRoute<void>(
182
                      builder: (BuildContext context) {
183 184
                        return SampleForm(
                          callback: () => Future<bool>.value(willPopValue),
185
                        );
186
                      },
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                    ));
                  },
                ),
              );
            },
          ),
        ),
      );
    }

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

  testWidgets('Form.willPop callbacks do not accumulate', (WidgetTester tester) async {
225 226
    Future<bool> showYesNoAlert(BuildContext context) async {
      return (await showDialog<bool>(
227
        context: context,
228
        builder: (BuildContext context) {
229
          return AlertDialog(
230
            actions: <Widget> [
231
              TextButton(
232
                child: const Text('YES'),
233
                onPressed: () { Navigator.of(context).pop(true); },
234
              ),
235
              TextButton(
236
                child: const Text('NO'),
237
                onPressed: () { Navigator.of(context).pop(false); },
238 239 240 241
              ),
            ],
          );
        },
242
      ))!;
243 244 245
    }

    Widget buildFrame() {
246 247 248 249
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
250
            builder: (BuildContext context) {
251
              return Center(
252
                child: TextButton(
253
                  child: const Text('X'),
254
                  onPressed: () {
255
                    Navigator.of(context).push(MaterialPageRoute<void>(
256
                      builder: (BuildContext context) {
257
                        return SampleForm(
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
                          callback: () => showYesNoAlert(context),
                        );
                      }
                    ));
                  },
                ),
              );
            },
          ),
        ),
      );
    }

    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
291 292 293 294
    // 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.
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    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);
  });

316
  testWidgets('Route.scopedWillPop callbacks do not accumulate', (WidgetTester tester) async {
317
    late StateSetter contentsSetState; // call this to rebuild the route's SampleForm contents
318 319
    bool contentsEmpty = false; // when true, don't include the SampleForm in the route

320
    final TestPageRoute<void> route = TestPageRoute<void>(
321
      builder: (BuildContext context) {
322
        return StatefulBuilder(
323 324
          builder: (BuildContext context, StateSetter setState) {
            contentsSetState = setState;
325
            return contentsEmpty ? Container() : SampleForm(key: UniqueKey(), callback: () async => false);
326 327 328 329 330 331
          }
        );
      },
    );

    Widget buildFrame() {
332 333 334 335
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Home')),
          body: Builder(
336
            builder: (BuildContext context) {
337
              return Center(
338
                child: TextButton(
339
                  child: const Text('X'),
340
                  onPressed: () {
341
                    Navigator.of(context).push(route);
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
                  },
                ),
              );
            },
          ),
        ),
      );
    }

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