inherited_model_test.dart 18.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 9 10 11 12 13
// 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/foundation.dart';
import 'package:flutter/material.dart';

// A simple "flat" InheritedModel: the data model is just 3 integer
// valued fields: a, b, c.
class ABCModel extends InheritedModel<String> {
  const ABCModel({
14
    Key? key,
15 16 17 18
    this.a,
    this.b,
    this.c,
    this.aspects,
19
    required Widget child,
20 21
  }) : super(key: key, child: child);

22 23 24
  final int? a;
  final int? b;
  final int? c;
25 26 27 28 29 30

  // The aspects (fields) of this model that widgets can depend on with
  // inheritFrom.
  //
  // This property is null by default, which means that the model supports
  // all 3 fields.
31
  final Set<String>? aspects;
32 33 34

  @override
  bool isSupportedAspect(Object aspect) {
35
    return aspect == null || aspects == null || aspects!.contains(aspect);
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
  }

  @override
  bool updateShouldNotify(ABCModel old) {
    return !setEquals<String>(aspects, old.aspects) || a != old.a || b != old.b || c != old.c;
  }

  @override
  bool updateShouldNotifyDependent(ABCModel old, Set<String> dependencies) {
    return !setEquals<String>(aspects, old.aspects)
        || (a != old.a && dependencies.contains('a'))
        || (b != old.b && dependencies.contains('b'))
        || (c != old.c && dependencies.contains('c'));
  }

51
  static ABCModel? of(BuildContext context, { String? fieldName }) {
52 53 54 55 56
    return InheritedModel.inheritFrom<ABCModel>(context, aspect: fieldName);
  }
}

class ShowABCField extends StatefulWidget {
57
  const ShowABCField({ Key? key, required this.fieldName }) : super(key: key);
58 59 60 61

  final String fieldName;

  @override
62
  _ShowABCFieldState createState() => _ShowABCFieldState();
63 64 65 66 67 68 69
}

class _ShowABCFieldState extends State<ShowABCField> {
  int _buildCount = 0;

  @override
  Widget build(BuildContext context) {
70 71
    final ABCModel abc = ABCModel.of(context, fieldName: widget.fieldName)!;
    final int? value = widget.fieldName == 'a' ? abc.a : (widget.fieldName == 'b' ? abc.b : abc.c);
72
    return Text('${widget.fieldName}: $value [${_buildCount++}]');
73 74 75 76 77 78 79 80 81
  }
}

void main() {
  testWidgets('InheritedModel basics', (WidgetTester tester) async {
    int _a = 0;
    int _b = 1;
    int _c = 2;

82
    final Widget abcPage = StatefulBuilder(
83 84 85 86 87 88 89
      builder: (BuildContext context, StateSetter setState) {
        const Widget showA = ShowABCField(fieldName: 'a');
        const Widget showB = ShowABCField(fieldName: 'b');
        const Widget showC = ShowABCField(fieldName: 'c');

        // Unconditionally depends on the ABCModel: rebuilt when any
        // aspect of the model changes.
90
        final Widget showABC = Builder(
91
          builder: (BuildContext context) {
92
            final ABCModel abc = ABCModel.of(context)!;
93
            return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}');
94 95 96
          }
        );

97 98
        return Scaffold(
          body: StatefulBuilder(
99
            builder: (BuildContext context, StateSetter setState) {
100
              return ABCModel(
101 102 103
                a: _a,
                b: _b,
                c: _c,
104 105
                child: Center(
                  child: Column(
106 107 108 109 110 111
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      showA,
                      showB,
                      showC,
                      showABC,
112
                      ElevatedButton(
113 114 115 116 117 118 119 120
                        child: const Text('Increment a'),
                        onPressed: () {
                          // Rebuilds the ABCModel which triggers a rebuild
                          // of showA because showA depends on the 'a' aspect
                          // of the ABCModel.
                          setState(() { _a += 1; });
                        },
                      ),
121
                      ElevatedButton(
122 123 124 125 126 127 128 129
                        child: const Text('Increment b'),
                        onPressed: () {
                          // Rebuilds the ABCModel which triggers a rebuild
                          // of showB because showB depends on the 'b' aspect
                          // of the ABCModel.
                          setState(() { _b += 1; });
                        },
                      ),
130
                      ElevatedButton(
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
                        child: const Text('Increment c'),
                        onPressed: () {
                          // Rebuilds the ABCModel which triggers a rebuild
                          // of showC because showC depends on the 'c' aspect
                          // of the ABCModel.
                          setState(() { _c += 1; });
                        },
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        );
      },
    );

149
    await tester.pumpWidget(MaterialApp(home: abcPage));
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

    expect(find.text('a: 0 [0]'), findsOneWidget);
    expect(find.text('b: 1 [0]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 0 b: 1 c: 2'), findsOneWidget);

    await tester.tap(find.text('Increment a'));
    await tester.pumpAndSettle();
    // Verify that field 'a' was incremented, but only the showA
    // and showABC widgets were rebuilt.
    expect(find.text('a: 1 [1]'), findsOneWidget);
    expect(find.text('b: 1 [0]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 1 b: 1 c: 2'), findsOneWidget);

    // Verify that field 'a' was incremented, but only the showA
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment a'));
    await tester.pumpAndSettle();
    expect(find.text('a: 2 [2]'), findsOneWidget);
    expect(find.text('b: 1 [0]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 2 b: 1 c: 2'), findsOneWidget);

    // Verify that field 'b' was incremented, but only the showB
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment b'));
    await tester.pumpAndSettle();
    expect(find.text('a: 2 [2]'), findsOneWidget);
    expect(find.text('b: 2 [1]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 2 b: 2 c: 2'), findsOneWidget);

    // Verify that field 'c' was incremented, but only the showC
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment c'));
    await tester.pumpAndSettle();
    expect(find.text('a: 2 [2]'), findsOneWidget);
    expect(find.text('b: 2 [1]'), findsOneWidget);
    expect(find.text('c: 3 [1]'), findsOneWidget);
    expect(find.text('a: 2 b: 2 c: 3'), findsOneWidget);
  });

193
  testWidgets('Looking up an non existent InheritedModel ancestor returns null', (WidgetTester tester) async {
194
    ABCModel? inheritedModel;
xster's avatar
xster committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208

    await tester.pumpWidget(
      Builder(
        builder: (BuildContext context) {
          inheritedModel = InheritedModel.inheritFrom(context);
          return Container();
        },
      ),
    );
    // Shouldn't crash first of all.

    expect(inheritedModel, null);
  });

209 210 211 212 213 214 215 216 217 218
  testWidgets('Inner InheritedModel shadows the outer one', (WidgetTester tester) async {
    int _a = 0;
    int _b = 1;
    int _c = 2;

    // Same as in abcPage in the "InheritedModel basics" test except:
    // there are two ABCModels and the inner model's "a" and "b"
    // properties shadow (override) the outer model. Further complicating
    // matters: the inner model only supports the model's "a" aspect,
    // so showB and showC will depend on the outer model.
219
    final Widget abcPage = StatefulBuilder(
220 221 222 223 224 225 226
      builder: (BuildContext context, StateSetter setState) {
        const Widget showA = ShowABCField(fieldName: 'a');
        const Widget showB = ShowABCField(fieldName: 'b');
        const Widget showC = ShowABCField(fieldName: 'c');

        // Unconditionally depends on the closest ABCModel ancestor.
        // Which is the inner model, for which b,c are null.
227
        final Widget showABC = Builder(
228
          builder: (BuildContext context) {
229
            final ABCModel abc = ABCModel.of(context)!;
230
            return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.headline6);
231 232 233
          }
        );

234 235
        return Scaffold(
          body: StatefulBuilder(
236
            builder: (BuildContext context, StateSetter setState) {
237
              return ABCModel( // The "outer" model
238 239 240
                a: _a,
                b: _b,
                c: _c,
241
                child: ABCModel( // The "inner" model
242 243
                  a: 100 + _a,
                  b: 100 + _b,
244
                  aspects: const <String>{'a'},
245 246
                  child: Center(
                    child: Column(
247 248 249 250 251 252 253 254
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        showA,
                        showB,
                        showC,
                        const SizedBox(height: 24.0),
                        showABC,
                        const SizedBox(height: 24.0),
255
                        ElevatedButton(
256 257 258 259 260
                          child: const Text('Increment a'),
                          onPressed: () {
                            setState(() { _a += 1; });
                          },
                        ),
261
                        ElevatedButton(
262 263 264 265 266
                          child: const Text('Increment b'),
                          onPressed: () {
                            setState(() { _b += 1; });
                          },
                        ),
267
                        ElevatedButton(
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
                          child: const Text('Increment c'),
                          onPressed: () {
                            setState(() { _c += 1; });
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );

284
    await tester.pumpWidget(MaterialApp(home: abcPage));
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 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    expect(find.text('a: 100 [0]'), findsOneWidget);
    expect(find.text('b: 1 [0]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 100 b: 101 c: null'), findsOneWidget);

    await tester.tap(find.text('Increment a'));
    await tester.pumpAndSettle();
    // Verify that field 'a' was incremented, but only the showA
    // and showABC widgets were rebuilt.
    expect(find.text('a: 101 [1]'), findsOneWidget);
    expect(find.text('b: 1 [0]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 101 b: 101 c: null'), findsOneWidget);

    await tester.tap(find.text('Increment a'));
    await tester.pumpAndSettle();
    // Verify that field 'a' was incremented, but only the showA
    // and showABC widgets were rebuilt.
    expect(find.text('a: 102 [2]'), findsOneWidget);
    expect(find.text('b: 1 [0]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 102 b: 101 c: null'), findsOneWidget);

    // Verify that field 'b' was incremented, but only the showB
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment b'));
    await tester.pumpAndSettle();
    expect(find.text('a: 102 [2]'), findsOneWidget);
    expect(find.text('b: 2 [1]'), findsOneWidget);
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 102 b: 102 c: null'), findsOneWidget);

    // Verify that field 'c' was incremented, but only the showC
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment c'));
    await tester.pumpAndSettle();
    expect(find.text('a: 102 [2]'), findsOneWidget);
    expect(find.text('b: 2 [1]'), findsOneWidget);
    expect(find.text('c: 3 [1]'), findsOneWidget);
    expect(find.text('a: 102 b: 102 c: null'), findsOneWidget);
  });

  testWidgets('InheritedModel inner models supported aspect change', (WidgetTester tester) async {
    int _a = 0;
    int _b = 1;
    int _c = 2;
331
    Set<String>? _innerModelAspects = <String>{'a'};
332 333 334 335

    // Same as in abcPage in the "Inner InheritedModel shadows the outer one"
    // test except: the "Add b aspect" changes adds 'b' to the set of
    // aspects supported by the inner model.
336
    final Widget abcPage = StatefulBuilder(
337 338 339 340 341 342 343
      builder: (BuildContext context, StateSetter setState) {
        const Widget showA = ShowABCField(fieldName: 'a');
        const Widget showB = ShowABCField(fieldName: 'b');
        const Widget showC = ShowABCField(fieldName: 'c');

        // Unconditionally depends on the closest ABCModel ancestor.
        // Which is the inner model, for which b,c are null.
344
        final Widget showABC = Builder(
345
          builder: (BuildContext context) {
346
            final ABCModel abc = ABCModel.of(context)!;
347
            return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.headline6);
348 349 350
          }
        );

351 352
        return Scaffold(
          body: StatefulBuilder(
353
            builder: (BuildContext context, StateSetter setState) {
354
              return ABCModel( // The "outer" model
355 356 357
                a: _a,
                b: _b,
                c: _c,
358
                child: ABCModel( // The "inner" model
359 360 361
                  a: 100 + _a,
                  b: 100 + _b,
                  aspects: _innerModelAspects,
362 363
                  child: Center(
                    child: Column(
364 365 366 367 368 369 370 371
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        showA,
                        showB,
                        showC,
                        const SizedBox(height: 24.0),
                        showABC,
                        const SizedBox(height: 24.0),
372
                        ElevatedButton(
373 374 375 376 377
                          child: const Text('Increment a'),
                          onPressed: () {
                            setState(() { _a += 1; });
                          },
                        ),
378
                        ElevatedButton(
379 380 381 382 383
                          child: const Text('Increment b'),
                          onPressed: () {
                            setState(() { _b += 1; });
                          },
                        ),
384
                        ElevatedButton(
385 386 387 388 389
                          child: const Text('Increment c'),
                          onPressed: () {
                            setState(() { _c += 1; });
                          },
                        ),
390
                        ElevatedButton(
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
                          child: const Text('rebuild'),
                          onPressed: () {
                            setState(() {
                              // Rebuild both models
                            });
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );

409
    _innerModelAspects = <String>{'a'};
410
    await tester.pumpWidget(MaterialApp(home: abcPage));
411 412 413 414 415
    expect(find.text('a: 100 [0]'), findsOneWidget); // showA depends on the inner model
    expect(find.text('b: 1 [0]'), findsOneWidget); // showB depends on the outer model
    expect(find.text('c: 2 [0]'), findsOneWidget);
    expect(find.text('a: 100 b: 101 c: null'), findsOneWidget); // inner model's a, b, c

416
    _innerModelAspects = <String>{'a', 'b'};
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    await tester.tap(find.text('rebuild'));
    await tester.pumpAndSettle();
    expect(find.text('a: 100 [1]'), findsOneWidget); // rebuilt showA still depend on the inner model
    expect(find.text('b: 101 [1]'), findsOneWidget); // rebuilt showB now depends on the inner model
    expect(find.text('c: 2 [1]'), findsOneWidget); // rebuilt showC still depends on the outer model
    expect(find.text('a: 100 b: 101 c: null'), findsOneWidget); // inner model's a, b, c

    // Verify that field 'a' was incremented, but only the showA
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment a'));
    await tester.pumpAndSettle();
    expect(find.text('a: 101 [2]'), findsOneWidget); // rebuilt showA still depends on the inner model
    expect(find.text('b: 101 [1]'), findsOneWidget);
    expect(find.text('c: 2 [1]'), findsOneWidget);
    expect(find.text('a: 101 b: 101 c: null'), findsOneWidget);

    // Verify that field 'b' was incremented, but only the showB
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment b'));
    await tester.pumpAndSettle();
    expect(find.text('a: 101 [2]'), findsOneWidget); // rebuilt showB still depends on the inner model
    expect(find.text('b: 102 [2]'), findsOneWidget);
    expect(find.text('c: 2 [1]'), findsOneWidget);
    expect(find.text('a: 101 b: 102 c: null'), findsOneWidget);

    // Verify that field 'c' was incremented, but only the showC
    // and showABC widgets were rebuilt.
    await tester.tap(find.text('Increment c'));
    await tester.pumpAndSettle();
    expect(find.text('a: 101 [2]'), findsOneWidget);
    expect(find.text('b: 102 [2]'), findsOneWidget);
    expect(find.text('c: 3 [2]'), findsOneWidget); // rebuilt showC still depends on the outer model
    expect(find.text('a: 101 b: 102 c: null'), findsOneWidget);

451
    _innerModelAspects = <String>{'a', 'b', 'c'};
452 453 454 455 456 457 458 459
    await tester.tap(find.text('rebuild'));
    await tester.pumpAndSettle();
    expect(find.text('a: 101 [3]'), findsOneWidget); // rebuilt showA still depend on the inner model
    expect(find.text('b: 102 [3]'), findsOneWidget); // rebuilt showB still depends on the inner model
    expect(find.text('c: null [3]'), findsOneWidget); // rebuilt showC now depends on the inner model
    expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c

    // Now the inner model supports no aspects
460
    _innerModelAspects = <String>{};
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    await tester.tap(find.text('rebuild'));
    await tester.pumpAndSettle();
    expect(find.text('a: 1 [4]'), findsOneWidget); // rebuilt showA now depends on the outer model
    expect(find.text('b: 2 [4]'), findsOneWidget); // rebuilt showB now depends on the outer model
    expect(find.text('c: 3 [4]'), findsOneWidget); // rebuilt showC now depends on the outer model
    expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c

    // Now the inner model supports all aspects
    _innerModelAspects = null;
    await tester.tap(find.text('rebuild'));
    await tester.pumpAndSettle();
    expect(find.text('a: 101 [5]'), findsOneWidget); // rebuilt showA now depends on the inner model
    expect(find.text('b: 102 [5]'), findsOneWidget); // rebuilt showB now depends on the inner model
    expect(find.text('c: null [5]'), findsOneWidget); // rebuilt showC now depends on the inner model
    expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c
  });
}