ticker_provider_test.dart 12.7 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
import 'package:flutter/foundation.dart';
6
import 'package:flutter/material.dart';
7
import 'package:flutter/scheduler.dart';
8 9 10 11
import 'package:flutter_test/flutter_test.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

  group('TickerProviderStateMixin assertion control test', () {
    testWidgets('SingleTickerProviderStateMixin create multiple tickers', (WidgetTester tester) async {
70
      const Widget widget = _SingleTickerCreateMultipleTicker();
71 72 73 74
      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
        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'
117
          'the ticker will leak.\n',
118
        );
Dan Field's avatar
Dan Field committed
119
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
120
        expect(error.toStringDeep().split('\n').take(13).join('\n'), equalsIgnoringHashCodes(
121 122 123 124 125 126 127 128 129 130 131
          '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'
132
            '     Ticker(created by _SingleTickerTestState#00000)\n'
133
            '     The stack trace when the Ticker was actually created was:',
134
        ));
135
        key.currentState!.controller.stop();
136 137 138 139 140
      }
    });

    testWidgets('SingleTickerProviderStateMixin dispose while active', (WidgetTester tester) async {
      final GlobalKey<_SingleTickerTestState> key = GlobalKey<_SingleTickerTestState>();
141
      final Widget widget = _SingleTickerTest(key: key);
142
      await tester.pumpWidget(widget);
143 144
      FlutterError? error;
      key.currentState!.controller.repeat();
145
      try {
146
        key.currentState!.dispose();
147 148 149 150
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
151
        expect(error!.diagnostics.length, 4);
152 153 154 155 156
        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'
157
          'the ticker will leak.\n',
158
        );
Dan Field's avatar
Dan Field committed
159
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
160
        expect(error.toStringDeep().split('\n').take(13).join('\n'), equalsIgnoringHashCodes(
161 162 163 164 165 166 167 168 169 170 171
          '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'
172
          '     Ticker(created by _SingleTickerTestState#00000)\n'
173
          '     The stack trace when the Ticker was actually created was:',
174
        ));
175
        key.currentState!.controller.stop();
176 177 178
      }
    });

179
    testWidgets('TickerProviderStateMixin dispose while any ticker is active', (WidgetTester tester) async {
180
      final GlobalKey<_MultipleTickerTestState> key = GlobalKey<_MultipleTickerTestState>();
181
      final Widget widget = _MultipleTickerTest(key: key);
182
      await tester.pumpWidget(widget);
183 184
      FlutterError? error;
      key.currentState!.controllers.first.repeat();
185
      try {
186
        key.currentState!.dispose();
187 188 189 190
      } on FlutterError catch (e) {
        error = e;
      } finally {
        expect(error, isNotNull);
191
        expect(error!.diagnostics.length, 4);
192 193 194 195 196
        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'
197
          'the ticker will leak.\n',
198
        );
Dan Field's avatar
Dan Field committed
199
        expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>());
200
        expect(error.toStringDeep().split('\n').take(12).join('\n'), equalsIgnoringHashCodes(
201 202 203 204 205 206 207 208 209 210 211
          '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'
212
          '     _WidgetTicker(created by _MultipleTickerTestState#00000)',
213
        ));
214
        key.currentState!.controllers.first.stop();
215 216 217
      }
    });
  });
218 219 220 221 222 223 224 225 226 227

  testWidgets('SingleTickerProviderStateMixin does not call State.toString', (WidgetTester tester) async {
    await tester.pumpWidget(const _SingleTickerTest());
    expect(tester.state<_SingleTickerTestState>(find.byType(_SingleTickerTest)).toStringCount, 0);
  });

  testWidgets('TickerProviderStateMixin does not call State.toString', (WidgetTester tester) async {
    await tester.pumpWidget(const _MultipleTickerTest());
    expect(tester.state<_MultipleTickerTestState>(find.byType(_MultipleTickerTest)).toStringCount, 0);
  });
228
}
229 230

class BoringTickerTest extends StatefulWidget {
231
  const BoringTickerTest({ super.key });
232
  @override
233
  State<BoringTickerTest> 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({super.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

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

  @override
  Widget build(BuildContext context) {
    return Container();
  }
264 265 266 267 268 269 270 271

  int toStringCount = 0;

  @override
  String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
    toStringCount += 1;
    return super.toString(minLevel: minLevel);
  }
272 273 274
}

class _MultipleTickerTest extends StatefulWidget {
275
  const _MultipleTickerTest({super.key});
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

  @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();
  }
296 297 298 299 300 301 302 303

  int toStringCount = 0;

  @override
  String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
    toStringCount += 1;
    return super.toString(minLevel: minLevel);
  }
304 305 306
}

class _SingleTickerCreateMultipleTicker extends StatefulWidget {
307 308
  const _SingleTickerCreateMultipleTicker();

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
  @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();
  }
}