form_test.dart 19.7 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
// 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';

void main() {
9
  testWidgets('onSaved callback is called', (WidgetTester tester) async {
10
    final GlobalKey<FormState> formKey = GlobalKey<FormState>();
11 12 13
    String fieldValue;

    Widget builder() {
14 15 16 17 18 19 20 21 22 23 24 25
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  key: formKey,
                  child: TextFormField(
                    onSaved: (String value) { fieldValue = value; },
                  ),
26
                ),
Ian Hickson's avatar
Ian Hickson committed
27
              ),
28
            ),
29 30
          ),
        ),
31 32
      );
    }
33

34
    await tester.pumpWidget(builder());
35

36
    expect(fieldValue, isNull);
37

38
    Future<void> checkText(String testValue) async {
39
      await tester.enterText(find.byType(TextFormField), testValue);
Matt Perry's avatar
Matt Perry committed
40
      formKey.currentState.save();
41
      // Pumping is unnecessary because callback happens regardless of frames.
42 43
      expect(fieldValue, equals(testValue));
    }
44

45 46
    await checkText('Test');
    await checkText('');
47 48
  });

49 50 51 52
  testWidgets('onChanged callback is called', (WidgetTester tester) async {
    String fieldValue;

    Widget builder() {
53 54 55 56 57 58 59 60 61 62 63
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  child: TextField(
                    onChanged: (String value) { fieldValue = value; },
                  ),
64
                ),
Ian Hickson's avatar
Ian Hickson committed
65
              ),
66
            ),
67 68
          ),
        ),
69 70 71 72 73 74 75
      );
    }

    await tester.pumpWidget(builder());

    expect(fieldValue, isNull);

76
    Future<void> checkText(String testValue) async {
77
      await tester.enterText(find.byType(TextField), testValue);
78 79 80 81 82 83 84 85
      // pump'ing is unnecessary because callback happens regardless of frames
      expect(fieldValue, equals(testValue));
    }

    await checkText('Test');
    await checkText('');
  });

86
  testWidgets('Validator sets the error text only when validate is called', (WidgetTester tester) async {
87
    final GlobalKey<FormState> formKey = GlobalKey<FormState>();
88
    String errorText(String value) => value + '/error';
89

90
    Widget builder(bool autovalidate) {
91 92 93 94 95 96 97 98 99 100 101 102 103
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  key: formKey,
                  autovalidate: autovalidate,
                  child: TextFormField(
                    validator: errorText,
                  ),
104
                ),
Ian Hickson's avatar
Ian Hickson committed
105
              ),
106
            ),
107 108
          ),
        ),
109 110
      );
    }
111

112 113
    // Start off not autovalidating.
    await tester.pumpWidget(builder(false));
114

115
    Future<void> checkErrorText(String testValue) async {
116 117
      formKey.currentState.reset();
      await tester.pumpWidget(builder(false));
118 119
      await tester.enterText(find.byType(TextFormField), testValue);
      await tester.pump();
120 121

      // We have to manually validate if we're not autovalidating.
122
      expect(find.text(errorText(testValue)), findsNothing);
123
      formKey.currentState.validate();
124
      await tester.pump();
125
      expect(find.text(errorText(testValue)), findsOneWidget);
126 127 128 129

      // Try again with autovalidation. Should validate immediately.
      formKey.currentState.reset();
      await tester.pumpWidget(builder(true));
130 131
      await tester.enterText(find.byType(TextFormField), testValue);
      await tester.pump();
132

133
      expect(find.text(errorText(testValue)), findsOneWidget);
134
    }
135

136 137
    await checkErrorText('Test');
    await checkErrorText('');
138 139
  });

140 141 142 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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 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 225 226 227 228 229 230 231 232 233
  testWidgets('isValid returns true when a field is valid', (WidgetTester tester) async {
    final GlobalKey<FormFieldState<String>> fieldKey1 = GlobalKey<FormFieldState<String>>();
    final GlobalKey<FormFieldState<String>> fieldKey2 = GlobalKey<FormFieldState<String>>();
    const String validString = 'Valid string';
    String validator(String s) => s == validString ? null : 'Error text';

    Widget builder() {
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  child: ListView(
                    children: <Widget>[
                      TextFormField(
                        key: fieldKey1,
                        initialValue: validString,
                        validator: validator,
                        autovalidate: true
                      ),
                      TextFormField(
                        key: fieldKey2,
                        initialValue: validString,
                        validator: validator,
                        autovalidate: true
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(builder());

    expect(fieldKey1.currentState.isValid, isTrue);
    expect(fieldKey2.currentState.isValid, isTrue);
  });

  testWidgets(
    'isValid returns false when the field is invalid and does not change error display',
    (WidgetTester tester) async {
      final GlobalKey<FormFieldState<String>> fieldKey1 = GlobalKey<FormFieldState<String>>();
      final GlobalKey<FormFieldState<String>> fieldKey2 = GlobalKey<FormFieldState<String>>();
      const String validString = 'Valid string';
      String validator(String s) => s == validString ? null : 'Error text';

      Widget builder() {
        return MaterialApp(
          home: MediaQuery(
            data: const MediaQueryData(devicePixelRatio: 1.0),
            child: Directionality(
              textDirection: TextDirection.ltr,
              child: Center(
                child: Material(
                  child: Form(
                    child: ListView(
                      children: <Widget>[
                        TextFormField(
                          key: fieldKey1,
                          initialValue: validString,
                          validator: validator,
                          autovalidate: false,
                        ),
                        TextFormField(
                          key: fieldKey2,
                          initialValue: '',
                          validator: validator,
                          autovalidate: false,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      }

      await tester.pumpWidget(builder());

      expect(fieldKey1.currentState.isValid, isTrue);
      expect(fieldKey2.currentState.isValid, isFalse);
      expect(fieldKey2.currentState.hasError, isFalse);
    },
  );

234
  testWidgets('Multiple TextFormFields communicate', (WidgetTester tester) async {
235 236
    final GlobalKey<FormState> formKey = GlobalKey<FormState>();
    final GlobalKey<FormFieldState<String>> fieldKey = GlobalKey<FormFieldState<String>>();
237
    // Input 2's validator depends on a input 1's value.
238
    String errorText(String input) => '${fieldKey.currentState.value}/error';
239 240

    Widget builder() {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  key: formKey,
                  autovalidate: true,
                  child: ListView(
                    children: <Widget>[
                      TextFormField(
                        key: fieldKey,
                      ),
                      TextFormField(
                        validator: errorText,
                      ),
                    ],
                  ),
261
                ),
262
              ),
263
            ),
264 265
          ),
        ),
266 267
      );
    }
268

269
    await tester.pumpWidget(builder());
270

271
    Future<void> checkErrorText(String testValue) async {
272
      await tester.enterText(find.byType(TextFormField).first, testValue);
273
      await tester.pump();
274

275
      // Check for a new Text widget with our error text.
Matt Perry's avatar
Matt Perry committed
276
      expect(find.text(testValue + '/error'), findsOneWidget);
277
      return;
278
    }
279

280 281
    await checkErrorText('Test');
    await checkErrorText('');
282
  });
283

284
  testWidgets('Provide initial value to input when no controller is specified', (WidgetTester tester) async {
285
    const String initialValue = 'hello';
286
    final GlobalKey<FormFieldState<String>> inputKey = GlobalKey<FormFieldState<String>>();
287 288

    Widget builder() {
289 290 291 292 293 294 295 296 297 298 299 300
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  child: TextFormField(
                    key: inputKey,
                    initialValue: 'hello',
                  ),
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
              ),
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(builder());
    await tester.showKeyboard(find.byType(TextFormField));

    // initial value should be loaded into keyboard editing state
    expect(tester.testTextInput.editingState, isNotNull);
    expect(tester.testTextInput.editingState['text'], equals(initialValue));

    // initial value should also be visible in the raw input line
    final EditableTextState editableText = tester.state(find.byType(EditableText));
    expect(editableText.widget.controller.text, equals(initialValue));

    // sanity check, make sure we can still edit the text and everything updates
    expect(inputKey.currentState.value, equals(initialValue));
    await tester.enterText(find.byType(TextFormField), 'world');
    await tester.pump();
    expect(inputKey.currentState.value, equals('world'));
    expect(editableText.widget.controller.text, equals('world'));
  });

328
  testWidgets('Controller defines initial value', (WidgetTester tester) async {
329
    final TextEditingController controller = TextEditingController(text: 'hello');
330
    const String initialValue = 'hello';
331
    final GlobalKey<FormFieldState<String>> inputKey = GlobalKey<FormFieldState<String>>();
332 333

    Widget builder() {
334 335 336 337 338 339 340 341 342 343 344 345
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  child: TextFormField(
                    key: inputKey,
                    controller: controller,
                  ),
346
                ),
Ian Hickson's avatar
Ian Hickson committed
347
              ),
348
            ),
349 350
          ),
        ),
351 352 353 354
      );
    }

    await tester.pumpWidget(builder());
355
    await tester.showKeyboard(find.byType(TextFormField));
356 357

    // initial value should be loaded into keyboard editing state
358 359
    expect(tester.testTextInput.editingState, isNotNull);
    expect(tester.testTextInput.editingState['text'], equals(initialValue));
360 361

    // initial value should also be visible in the raw input line
362
    final EditableTextState editableText = tester.state(find.byType(EditableText));
363
    expect(editableText.widget.controller.text, equals(initialValue));
364
    expect(controller.text, equals(initialValue));
365 366

    // sanity check, make sure we can still edit the text and everything updates
367
    expect(inputKey.currentState.value, equals(initialValue));
368
    await tester.enterText(find.byType(TextFormField), 'world');
369
    await tester.pump();
370
    expect(inputKey.currentState.value, equals('world'));
371
    expect(editableText.widget.controller.text, equals('world'));
372 373 374 375
    expect(controller.text, equals('world'));
  });

  testWidgets('TextFormField resets to its initial value', (WidgetTester tester) async {
376 377 378
    final GlobalKey<FormState> formKey = GlobalKey<FormState>();
    final GlobalKey<FormFieldState<String>> inputKey = GlobalKey<FormFieldState<String>>();
    final TextEditingController controller = TextEditingController(text: 'Plover');
379 380

    Widget builder() {
381 382 383 384 385 386 387 388 389 390 391 392 393 394
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  key: formKey,
                  child: TextFormField(
                    key: inputKey,
                    controller: controller,
                    // initialValue is 'Plover'
                  ),
395
                ),
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
              ),
            ),
          ),
        ),
      );
    }
    await tester.pumpWidget(builder());
    await tester.showKeyboard(find.byType(TextFormField));
    final EditableTextState editableText = tester.state(find.byType(EditableText));

    // overwrite initial value.
    controller.text = 'Xyzzy';
    await tester.idle();
    expect(editableText.widget.controller.text, equals('Xyzzy'));
    expect(inputKey.currentState.value, equals('Xyzzy'));
    expect(controller.text, equals('Xyzzy'));

    // verify value resets to initialValue on reset.
    formKey.currentState.reset();
    await tester.idle();
416 417 418
    expect(inputKey.currentState.value, equals('Plover'));
    expect(editableText.widget.controller.text, equals('Plover'));
    expect(controller.text, equals('Plover'));
419 420 421
  });

  testWidgets('TextEditingController updates to/from form field value', (WidgetTester tester) async {
422 423 424
    final TextEditingController controller1 = TextEditingController(text: 'Foo');
    final TextEditingController controller2 = TextEditingController(text: 'Bar');
    final GlobalKey<FormFieldState<String>> inputKey = GlobalKey<FormFieldState<String>>();
425 426 427 428 429

    TextEditingController currentController;
    StateSetter setState;

    Widget builder() {
430
      return StatefulBuilder(
431 432
        builder: (BuildContext context, StateSetter setter) {
          setState = setter;
433 434 435 436 437 438 439 440 441 442 443 444
          return MaterialApp(
            home: MediaQuery(
              data: const MediaQueryData(devicePixelRatio: 1.0),
              child: Directionality(
                textDirection: TextDirection.ltr,
                child: Center(
                  child: Material(
                    child: Form(
                      child: TextFormField(
                        key: inputKey,
                        controller: currentController,
                      ),
445
                    ),
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
                  ),
                ),
              ),
            ),
          );
        },
      );
    }

    await tester.pumpWidget(builder());
    await tester.showKeyboard(find.byType(TextFormField));

    // verify initially empty.
    expect(tester.testTextInput.editingState, isNotNull);
    expect(tester.testTextInput.editingState['text'], isEmpty);
    final EditableTextState editableText = tester.state(find.byType(EditableText));
    expect(editableText.widget.controller.text, isEmpty);

    // verify changing the controller from null to controller1 sets the value.
    setState(() {
      currentController = controller1;
    });
    await tester.pump();
    expect(editableText.widget.controller.text, equals('Foo'));
    expect(inputKey.currentState.value, equals('Foo'));

    // verify changes to controller1 text are visible in text field and set in form value.
    controller1.text = 'Wobble';
    await tester.idle();
    expect(editableText.widget.controller.text, equals('Wobble'));
    expect(inputKey.currentState.value, equals('Wobble'));

    // verify changes to the field text update the form value and controller1.
    await tester.enterText(find.byType(TextFormField), 'Wibble');
    await tester.pump();
    expect(inputKey.currentState.value, equals('Wibble'));
    expect(editableText.widget.controller.text, equals('Wibble'));
    expect(controller1.text, equals('Wibble'));

    // verify that switching from controller1 to controller2 is handled.
    setState(() {
      currentController = controller2;
    });
    await tester.pump();
    expect(inputKey.currentState.value, equals('Bar'));
    expect(editableText.widget.controller.text, equals('Bar'));
    expect(controller2.text, equals('Bar'));
    expect(controller1.text, equals('Wibble'));

    // verify changes to controller2 text are visible in text field and set in form value.
    controller2.text = 'Xyzzy';
    await tester.idle();
    expect(editableText.widget.controller.text, equals('Xyzzy'));
    expect(inputKey.currentState.value, equals('Xyzzy'));
    expect(controller1.text, equals('Wibble'));

    // verify changes to controller1 text are not visible in text field or set in form value.
    controller1.text = 'Plugh';
    await tester.idle();
    expect(editableText.widget.controller.text, equals('Xyzzy'));
    expect(inputKey.currentState.value, equals('Xyzzy'));
    expect(controller1.text, equals('Plugh'));

    // verify that switching from controller2 to null is handled.
    setState(() {
      currentController = null;
    });
    await tester.pump();
    expect(inputKey.currentState.value, equals('Xyzzy'));
    expect(editableText.widget.controller.text, equals('Xyzzy'));
    expect(controller2.text, equals('Xyzzy'));
    expect(controller1.text, equals('Plugh'));

    // verify that changes to the field text update the form value but not the previous controllers.
    await tester.enterText(find.byType(TextFormField), 'Plover');
    await tester.pump();
    expect(inputKey.currentState.value, equals('Plover'));
    expect(editableText.widget.controller.text, equals('Plover'));
    expect(controller1.text, equals('Plugh'));
    expect(controller2.text, equals('Xyzzy'));
Matt Perry's avatar
Matt Perry committed
526 527
  });

528
  testWidgets('No crash when a TextFormField is removed from the tree', (WidgetTester tester) async {
529
    final GlobalKey<FormState> formKey = GlobalKey<FormState>();
Matt Perry's avatar
Matt Perry committed
530 531 532
    String fieldValue;

    Widget builder(bool remove) {
533 534 535 536 537 538 539 540 541 542 543 544 545 546
      return MaterialApp(
        home: MediaQuery(
          data: const MediaQueryData(devicePixelRatio: 1.0),
          child: Directionality(
            textDirection: TextDirection.ltr,
            child: Center(
              child: Material(
                child: Form(
                  key: formKey,
                  child: remove ? Container() : TextFormField(
                    autofocus: true,
                    onSaved: (String value) { fieldValue = value; },
                    validator: (String value) { return value.isEmpty ? null : 'yes'; },
                  ),
547
                ),
Ian Hickson's avatar
Ian Hickson committed
548
              ),
549
            ),
550 551
          ),
        ),
Matt Perry's avatar
Matt Perry committed
552 553 554 555 556 557
      );
    }

    await tester.pumpWidget(builder(false));

    expect(fieldValue, isNull);
558
    expect(formKey.currentState.validate(), isTrue);
Matt Perry's avatar
Matt Perry committed
559

560
    await tester.enterText(find.byType(TextFormField), 'Test');
Matt Perry's avatar
Matt Perry committed
561 562
    await tester.pumpWidget(builder(false));

563
    // Form wasn't saved yet.
Matt Perry's avatar
Matt Perry committed
564
    expect(fieldValue, null);
565
    expect(formKey.currentState.validate(), isFalse);
Matt Perry's avatar
Matt Perry committed
566 567 568 569 570

    formKey.currentState.save();

    // Now fieldValue is saved.
    expect(fieldValue, 'Test');
571
    expect(formKey.currentState.validate(), isFalse);
Matt Perry's avatar
Matt Perry committed
572 573 574

    // Now remove the field with an error.
    await tester.pumpWidget(builder(true));
575

Matt Perry's avatar
Matt Perry committed
576 577 578
    // Reset the form. Should not crash.
    formKey.currentState.reset();
    formKey.currentState.save();
579
    expect(formKey.currentState.validate(), isTrue);
580
  });
581
}