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

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

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

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

  // 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.
30
  final Set<String>? aspects;
31 32 33

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

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

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

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

  final String fieldName;

  @override
61
  State<ShowABCField> createState() => _ShowABCFieldState();
62 63 64 65 66 67 68
}

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

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

void main() {
  testWidgets('InheritedModel basics', (WidgetTester tester) async {
77 78 79
    int a = 0;
    int b = 1;
    int c = 2;
80

81
    final Widget abcPage = StatefulBuilder(
82 83 84 85 86 87 88
      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.
89
        final Widget showABC = Builder(
90
          builder: (BuildContext context) {
91
            final ABCModel abc = ABCModel.of(context)!;
92
            return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}');
93
          },
94 95
        );

96 97
        return Scaffold(
          body: StatefulBuilder(
98
            builder: (BuildContext context, StateSetter setState) {
99
              return ABCModel(
100 101 102
                a: a,
                b: b,
                c: c,
103 104
                child: Center(
                  child: Column(
105 106 107 108 109 110
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      showA,
                      showB,
                      showC,
                      showABC,
111
                      ElevatedButton(
112 113 114 115 116
                        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.
117
                          setState(() { a += 1; });
118 119
                        },
                      ),
120
                      ElevatedButton(
121 122 123 124 125
                        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.
126
                          setState(() { b += 1; });
127 128
                        },
                      ),
129
                      ElevatedButton(
130 131 132 133 134
                        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.
135
                          setState(() { c += 1; });
136 137 138 139 140 141 142 143 144 145 146 147
                        },
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        );
      },
    );

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

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

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

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

    expect(inheritedModel, null);
  });

208
  testWidgets('Inner InheritedModel shadows the outer one', (WidgetTester tester) async {
209 210 211
    int a = 0;
    int b = 1;
    int c = 2;
212 213 214 215 216 217

    // 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.
218
    final Widget abcPage = StatefulBuilder(
219 220 221 222 223 224 225
      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.
226
        final Widget showABC = Builder(
227
          builder: (BuildContext context) {
228
            final ABCModel abc = ABCModel.of(context)!;
229
            return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.titleLarge);
230
          },
231 232
        );

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

283
    await tester.pumpWidget(MaterialApp(home: abcPage));
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 315 316 317 318 319 320 321 322 323 324 325 326
    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 {
327 328 329 330
    int a = 0;
    int b = 1;
    int c = 2;
    Set<String>? innerModelAspects = <String>{'a'};
331 332 333 334

    // 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.
335
    final Widget abcPage = StatefulBuilder(
336 337 338 339 340 341 342
      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.
343
        final Widget showABC = Builder(
344
          builder: (BuildContext context) {
345
            final ABCModel abc = ABCModel.of(context)!;
346
            return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.titleLarge);
347
          },
348 349
        );

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

408
    innerModelAspects = <String>{'a'};
409
    await tester.pumpWidget(MaterialApp(home: abcPage));
410 411 412 413 414
    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

415
    innerModelAspects = <String>{'a', 'b'};
416 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
    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);

450
    innerModelAspects = <String>{'a', 'b', 'c'};
451 452 453 454 455 456 457 458
    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
459
    innerModelAspects = <String>{};
460 461 462 463 464 465 466 467
    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
468
    innerModelAspects = null;
469 470 471 472 473 474 475 476
    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
  });
}