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

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

void main() {
  testWidgets('TickerMode', (WidgetTester tester) async {
12
    const Widget widget = TickerMode(
13
      enabled: false,
14
      child: CircularProgressIndicator(),
15 16 17 18
    );
    expect(widget.toString, isNot(throwsException));

    await tester.pumpWidget(widget);
19 20 21

    expect(tester.binding.transientCallbackCount, 0);

22
    await tester.pumpWidget(const TickerMode(
23
      enabled: true,
24
      child: CircularProgressIndicator(),
25 26 27 28
    ));

    expect(tester.binding.transientCallbackCount, 1);

29
    await tester.pumpWidget(const TickerMode(
30
      enabled: false,
31
      child: CircularProgressIndicator(),
32 33 34 35 36 37
    ));

    expect(tester.binding.transientCallbackCount, 0);
  });

  testWidgets('Navigation with TickerMode', (WidgetTester tester) async {
38
    await tester.pumpWidget(MaterialApp(
39
      home: const LinearProgressIndicator(),
40
      routes: <String, WidgetBuilder>{
41
        '/test': (BuildContext context) => const Text('hello'),
42 43 44
      },
    ));
    expect(tester.binding.transientCallbackCount, 1);
45
    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/test');
46 47 48 49 50
    expect(tester.binding.transientCallbackCount, 2);
    await tester.pump();
    expect(tester.binding.transientCallbackCount, 2);
    await tester.pump(const Duration(seconds: 5));
    expect(tester.binding.transientCallbackCount, 0);
51
    tester.state<NavigatorState>(find.byType(Navigator)).pop();
52 53 54 55 56 57
    expect(tester.binding.transientCallbackCount, 1);
    await tester.pump();
    expect(tester.binding.transientCallbackCount, 2);
    await tester.pump(const Duration(seconds: 5));
    expect(tester.binding.transientCallbackCount, 1);
  });
58 59

  testWidgets('SingleTickerProviderStateMixin can handle not being used', (WidgetTester tester) async {
60
    const Widget widget = BoringTickerTest();
61 62 63
    expect(widget.toString, isNot(throwsException));

    await tester.pumpWidget(widget);
64
    await tester.pumpWidget(Container());
65 66
    // the test is that this doesn't crash, like it used to...
  });
67 68 69 70 71 72 73 74

  group('TickerProviderStateMixin assertion control test', () {
    testWidgets('SingleTickerProviderStateMixin create multiple tickers', (WidgetTester tester) async {
      final Widget widget = _SingleTickerCreateMultipleTicker();
      await tester.pumpWidget(widget);
      final dynamic exception = tester.takeException();
      expect(exception, isNotNull);
      expect(exception, isFlutterError);
75
      final FlutterError error = exception as FlutterError;
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
      expect(error.diagnostics.length, 3);
      expect(error.diagnostics[2].level, DiagnosticLevel.hint);
      expect(error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes(
        'If a State is used for multiple AnimationController objects, or\n'
        'if it is passed to other objects and those objects might use it\n'
        'more than one time in total, then instead of mixing in a\n'
        'SingleTickerProviderStateMixin, use a regular\n'
        'TickerProviderStateMixin.\n',
      ));
      expect(error.toStringDeep(), equalsIgnoringHashCodes(
        'FlutterError\n'
        '   _SingleTickerCreateMultipleTickerState is a\n'
        '   SingleTickerProviderStateMixin but multiple tickers were created.\n'
        '   A SingleTickerProviderStateMixin can only be used as a\n'
        '   TickerProvider once.\n'
        '   If a State is used for multiple AnimationController objects, or\n'
        '   if it is passed to other objects and those objects might use it\n'
        '   more than one time in total, then instead of mixing in a\n'
        '   SingleTickerProviderStateMixin, use a regular\n'
        '   TickerProviderStateMixin.\n',
      ));
    });

    testWidgets('SingleTickerProviderStateMixin dispose while active', (WidgetTester tester) async {
      final GlobalKey<_SingleTickerTestState> key = GlobalKey<_SingleTickerTestState>();
      final Widget widget = Container(
        child: _SingleTickerTest(key: key),
      );
      await tester.pumpWidget(widget);
105 106
      FlutterError? error;
      key.currentState!.controller.repeat();
107
      try {
108
        key.currentState!.dispose();
109 110 111 112
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
113
        expect(error!.diagnostics.length, 4);
114 115 116 117 118 119 120
        expect(error.diagnostics[2].level, DiagnosticLevel.hint);
        expect(
          error.diagnostics[2].toStringDeep(),
          'Tickers used by AnimationControllers should be disposed by\n'
          'calling dispose() on the AnimationController itself. Otherwise,\n'
          'the ticker will leak.\n'
        );
Dan Field's avatar
Dan Field committed
121
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        expect(error.toStringDeep().split('\n').take(14).join('\n'), equalsIgnoringHashCodes(
          'FlutterError\n'
            '   _SingleTickerTestState#00000(ticker active) was disposed with an\n'
            '   active Ticker.\n'
            '   _SingleTickerTestState created a Ticker via its\n'
            '   SingleTickerProviderStateMixin, but at the time dispose() was\n'
            '   called on the mixin, that Ticker was still active. The Ticker\n'
            '   must be disposed before calling super.dispose().\n'
            '   Tickers used by AnimationControllers should be disposed by\n'
            '   calling dispose() on the AnimationController itself. Otherwise,\n'
            '   the ticker will leak.\n'
            '   The offending ticker was:\n'
            '     Ticker(created by _SingleTickerTestState#00000(lifecycle state:\n'
            '     created))\n'
            '     The stack trace when the Ticker was actually created was:'
        ));
138
        key.currentState!.controller.stop();
139 140 141 142 143 144 145 146 147
      }
    });

    testWidgets('SingleTickerProviderStateMixin dispose while active', (WidgetTester tester) async {
      final GlobalKey<_SingleTickerTestState> key = GlobalKey<_SingleTickerTestState>();
      final Widget widget = Container(
        child: _SingleTickerTest(key: key),
      );
      await tester.pumpWidget(widget);
148 149
      FlutterError? error;
      key.currentState!.controller.repeat();
150
      try {
151
        key.currentState!.dispose();
152 153 154 155
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
156
        expect(error!.diagnostics.length, 4);
157 158 159 160 161 162 163
        expect(error.diagnostics[2].level, DiagnosticLevel.hint);
        expect(
          error.diagnostics[2].toStringDeep(),
          'Tickers used by AnimationControllers should be disposed by\n'
          'calling dispose() on the AnimationController itself. Otherwise,\n'
          'the ticker will leak.\n'
        );
Dan Field's avatar
Dan Field committed
164
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        expect(error.toStringDeep().split('\n').take(14).join('\n'), equalsIgnoringHashCodes(
          'FlutterError\n'
          '   _SingleTickerTestState#00000(ticker active) was disposed with an\n'
          '   active Ticker.\n'
          '   _SingleTickerTestState created a Ticker via its\n'
          '   SingleTickerProviderStateMixin, but at the time dispose() was\n'
          '   called on the mixin, that Ticker was still active. The Ticker\n'
          '   must be disposed before calling super.dispose().\n'
          '   Tickers used by AnimationControllers should be disposed by\n'
          '   calling dispose() on the AnimationController itself. Otherwise,\n'
          '   the ticker will leak.\n'
          '   The offending ticker was:\n'
          '     Ticker(created by _SingleTickerTestState#00000(lifecycle state:\n'
          '     created))\n'
          '     The stack trace when the Ticker was actually created was:'
        ));
181
        key.currentState!.controller.stop();
182 183 184 185 186 187 188 189 190
      }
    });

    testWidgets('ProviderStateMixin dispose while any ticker is active', (WidgetTester tester) async {
      final GlobalKey<_MultipleTickerTestState> key = GlobalKey<_MultipleTickerTestState>();
      final Widget widget = Container(
        child: _MultipleTickerTest(key: key),
      );
      await tester.pumpWidget(widget);
191 192
      FlutterError? error;
      key.currentState!.controllers.first.repeat();
193
      try {
194
        key.currentState!.dispose();
195 196 197 198
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
199
        expect(error!.diagnostics.length, 4);
200 201 202 203 204 205 206
        expect(error.diagnostics[2].level, DiagnosticLevel.hint);
        expect(
          error.diagnostics[2].toStringDeep(),
          'Tickers used by AnimationControllers should be disposed by\n'
          'calling dispose() on the AnimationController itself. Otherwise,\n'
          'the ticker will leak.\n'
        );
Dan Field's avatar
Dan Field committed
207
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        expect(error.toStringDeep().split('\n').take(14).join('\n'), equalsIgnoringHashCodes(
          'FlutterError\n'
          '   _MultipleTickerTestState#00000(tickers: tracking 2 tickers) was\n'
          '   disposed with an active Ticker.\n'
          '   _MultipleTickerTestState created a Ticker via its\n'
          '   TickerProviderStateMixin, but at the time dispose() was called on\n'
          '   the mixin, that Ticker was still active. All Tickers must be\n'
          '   disposed before calling super.dispose().\n'
          '   Tickers used by AnimationControllers should be disposed by\n'
          '   calling dispose() on the AnimationController itself. Otherwise,\n'
          '   the ticker will leak.\n'
          '   The offending ticker was:\n'
          '     _WidgetTicker(created by\n'
          '     _MultipleTickerTestState#00000(lifecycle state: created,\n'
          '     tickers: tracking 0 tickers))'
        ));
224
        key.currentState!.controllers.first.stop();
225 226 227
      }
    });
  });
228
}
229 230

class BoringTickerTest extends StatefulWidget {
231
  const BoringTickerTest({ Key? key }) : super(key: key);
232
  @override
233
  _BoringTickerTestState createState() => _BoringTickerTestState();
234 235 236 237
}

class _BoringTickerTestState extends State<BoringTickerTest> with SingleTickerProviderStateMixin {
  @override
238
  Widget build(BuildContext context) => Container();
239
}
240 241

class _SingleTickerTest extends StatefulWidget {
242
  const _SingleTickerTest({Key? key}) : super(key: key);
243 244 245 246 247 248

  @override
  _SingleTickerTestState createState() => _SingleTickerTestState();
}

class _SingleTickerTestState extends State<_SingleTickerTest> with SingleTickerProviderStateMixin {
249
  late AnimationController controller;
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 100),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class _MultipleTickerTest extends StatefulWidget {
267
  const _MultipleTickerTest({Key? key}) : super(key: key);
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 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

  @override
  _MultipleTickerTestState createState() => _MultipleTickerTestState();
}

class _MultipleTickerTestState extends State<_MultipleTickerTest> with TickerProviderStateMixin {
  List<AnimationController> controllers = <AnimationController>[];

  @override
  void initState() {
    super.initState();
    const Duration duration = Duration(seconds: 100);
    controllers.add(AnimationController(vsync: this, duration: duration));
    controllers.add(AnimationController(vsync: this, duration: duration));
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class _SingleTickerCreateMultipleTicker extends StatefulWidget {
  @override
  _SingleTickerCreateMultipleTickerState createState() => _SingleTickerCreateMultipleTickerState();
}

class _SingleTickerCreateMultipleTickerState extends State<_SingleTickerCreateMultipleTicker> with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
    AnimationController(
      duration: const Duration(seconds: 5),
      vsync: this,
    );
    AnimationController(
      duration: const Duration(seconds: 6),
      vsync: this,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}