will_pop_test.dart 10.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright 2016 The Chromium Authors. All rights reserved.
// 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 {
  @override
  SamplePageState createState() => new SamplePageState();
}

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

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

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

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

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

int willPopCount = 0;

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

  final WillPopCallback callback;

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

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

  bool get hasCallback => super.hasScopedWillPopCallback;
}


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

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

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

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

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

  testWidgets('Form.willPop can inhibit back button', (WidgetTester tester) async {
    Widget buildFrame() {
      return new MaterialApp(
        home: new Scaffold(
134
          appBar: new AppBar(title: const Text('Home')),
135 136 137 138
          body: new Builder(
            builder: (BuildContext context) {
              return new Center(
                child: new FlatButton(
139
                  child: const Text('X'),
140
                  onPressed: () {
141
                    Navigator.of(context).push(new MaterialPageRoute<void>(
142 143 144 145
                      builder: (BuildContext context) {
                        return new SampleForm(
                          callback: () => new Future<bool>.value(willPopValue),
                        );
146
                      },
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
                    ));
                  },
                ),
              );
            },
          ),
        ),
      );
    }

    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 {
    Future<bool> showYesNoAlert(BuildContext context) {
186
      return showDialog<bool>(
187
        context: context,
188 189 190 191 192 193 194 195 196 197 198 199 200 201
        builder: (BuildContext context) {
          return new AlertDialog(
            actions: <Widget> [
              new FlatButton(
                child: const Text('YES'),
                onPressed: () { Navigator.of(context).pop(true); },
              ),
              new FlatButton(
                child: const Text('NO'),
                onPressed: () { Navigator.of(context).pop(false); },
              ),
            ],
          );
        },
202 203 204 205 206 207
      );
    }

    Widget buildFrame() {
      return new MaterialApp(
        home: new Scaffold(
208
          appBar: new AppBar(title: const Text('Home')),
209 210 211 212
          body: new Builder(
            builder: (BuildContext context) {
              return new Center(
                child: new FlatButton(
213
                  child: const Text('X'),
214
                  onPressed: () {
215
                    Navigator.of(context).push(new MaterialPageRoute<void>(
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 248 249 250 251
                      builder: (BuildContext context) {
                        return new SampleForm(
                          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);

    // Do it again. Note that each time the Alert is shown and dismissed
252 253
    // the FormState's didChangeDependencies() method runs. We're making sure
    // that the didChangeDependencies() method doesn't add an extra willPop
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    // callback.
    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);
  });

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

280
    final TestPageRoute<Null> route = new TestPageRoute<Null>(
281 282 283 284 285 286 287 288 289 290 291 292 293
      builder: (BuildContext context) {
        return new StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            contentsSetState = setState;
            return contentsEmpty ? new Container() : new SampleForm(key: new UniqueKey());
          }
        );
      },
    );

    Widget buildFrame() {
      return new MaterialApp(
        home: new Scaffold(
294
          appBar: new AppBar(title: const Text('Home')),
295 296 297 298
          body: new Builder(
            builder: (BuildContext context) {
              return new Center(
                child: new FlatButton(
299
                  child: const Text('X'),
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
                  onPressed: () {
                    Navigator.of(context).push(route);
                  },
                ),
              );
            },
          ),
        ),
      );
    }

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