ticker_provider_test.dart 12 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
      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>();
101
      final Widget widget = _SingleTickerTest(key: key);
102
      await tester.pumpWidget(widget);
103 104
      FlutterError? error;
      key.currentState!.controller.repeat();
105
      try {
106
        key.currentState!.dispose();
107 108 109 110
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
111
        expect(error!.diagnostics.length, 4);
112 113 114 115 116 117 118
        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
119
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        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:'
        ));
136
        key.currentState!.controller.stop();
137 138 139 140 141
      }
    });

    testWidgets('SingleTickerProviderStateMixin dispose while active', (WidgetTester tester) async {
      final GlobalKey<_SingleTickerTestState> key = GlobalKey<_SingleTickerTestState>();
142
      final Widget widget = _SingleTickerTest(key: key);
143
      await tester.pumpWidget(widget);
144 145
      FlutterError? error;
      key.currentState!.controller.repeat();
146
      try {
147
        key.currentState!.dispose();
148 149 150 151
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
152
        expect(error!.diagnostics.length, 4);
153 154 155 156 157 158 159
        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
160
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        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:'
        ));
177
        key.currentState!.controller.stop();
178 179 180 181 182
      }
    });

    testWidgets('ProviderStateMixin dispose while any ticker is active', (WidgetTester tester) async {
      final GlobalKey<_MultipleTickerTestState> key = GlobalKey<_MultipleTickerTestState>();
183
      final Widget widget = _MultipleTickerTest(key: key);
184
      await tester.pumpWidget(widget);
185 186
      FlutterError? error;
      key.currentState!.controllers.first.repeat();
187
      try {
188
        key.currentState!.dispose();
189 190 191 192
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
193
        expect(error!.diagnostics.length, 4);
194 195 196 197 198 199 200
        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
201
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        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))'
        ));
218
        key.currentState!.controllers.first.stop();
219 220 221
      }
    });
  });
222
}
223 224

class BoringTickerTest extends StatefulWidget {
225
  const BoringTickerTest({ Key? key }) : super(key: key);
226
  @override
227
  _BoringTickerTestState createState() => _BoringTickerTestState();
228 229 230 231
}

class _BoringTickerTestState extends State<BoringTickerTest> with SingleTickerProviderStateMixin {
  @override
232
  Widget build(BuildContext context) => Container();
233
}
234 235

class _SingleTickerTest extends StatefulWidget {
236
  const _SingleTickerTest({Key? key}) : super(key: key);
237 238 239 240 241 242

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

class _SingleTickerTestState extends State<_SingleTickerTest> with SingleTickerProviderStateMixin {
243
  late AnimationController controller;
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

  @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 {
261
  const _MultipleTickerTest({Key? key}) : super(key: key);
262 263 264 265 266 267 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

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