Skip to content

Test fails due to pending timer when using ShadApp.material in Flutter counter app example #294

@pingebat

Description

@pingebat

Steps to reproduce

  1. Create a new Flutter project using flutter create counter_app.
  2. Replace the MaterialApp in lib/main.dart with ShadApp.material.
  3. Run the default test (test/widget_test.dart) using flutter test.

Code Example:
Here is the modified lib/main.dart:

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ShadApp.material(
      title: 'Flutter Demo',
      
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Expected results

The test should pass without any errors, just as it does when using MaterialApp.

Actual results

The test fails with the following error:

A Timer is still pending even after the widget tree was disposed.
'package:flutter_test/src/binding.dart':
Failed assertion: line 1537 pos 12: '!timersPending'

shadcn_ui version

0.19.3

Platform

MacOS

Code sample

Code sample

Here is the modified lib/main.dart:

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ShadApp.material(
      title: 'Flutter Demo',
      
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Pending timers:
Timer (duration: 0:00:00.000000, periodic: false), created:
#0      new FakeTimer._ (package:fake_async/fake_async.dart:308:62)
#1      FakeAsync._createTimer (package:fake_async/fake_async.dart:252:27)
#2      FakeAsync.run.<anonymous closure> (package:fake_async/fake_async.dart:185:19)
#6      _AnimateState._restart (package:flutter_animate/src/animate.dart:318:23)
#7      _AnimateState.initState (package:flutter_animate/src/animate.dart:290:5)
#8      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5762:55)
#9      ComponentElement.mount (package:flutter/src/widgets/framework.dart:5607:5)
...     Normal element mounting (17 frames)
#26     Element.inflateWidget (package:flutter/src/widgets/framework.dart:4480:16)
#27     MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:7049:36)
#28     MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:7061:32)
...     Normal element mounting (464 frames)
#492    Element.inflateWidget (package:flutter/src/widgets/framework.dart:4480:16)
#493    Element.updateChild (package:flutter/src/widgets/framework.dart:3957:20)
#494    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#495    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#496    ProxyElement.update (package:flutter/src/widgets/framework.dart:5960:5)
#497    _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:112:11)
#498    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#499    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#500    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5794:11)
#501    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#502    StatefulElement.update (package:flutter/src/widgets/framework.dart:5817:5)
#503    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#504    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#505    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#506    ProxyElement.update (package:flutter/src/widgets/framework.dart:5960:5)
#507    _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:112:11)
#508    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#509    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#510    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5794:11)
#511    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#512    StatefulElement.update (package:flutter/src/widgets/framework.dart:5817:5)
#513    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#514    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#515    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5794:11)
#516    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#517    StatefulElement.update (package:flutter/src/widgets/framework.dart:5817:5)
#518    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#519    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#520    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#521    ProxyElement.update (package:flutter/src/widgets/framework.dart:5960:5)
#522    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#523    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#524    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5794:11)
#525    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#526    StatefulElement.update (package:flutter/src/widgets/framework.dart:5817:5)
#527    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#528    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#529    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#530    ProxyElement.update (package:flutter/src/widgets/framework.dart:5960:5)
#531    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#532    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#533    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#534    ProxyElement.update (package:flutter/src/widgets/framework.dart:5960:5)
#535    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#536    _RawViewElement._updateChild (package:flutter/src/widgets/view.dart:465:16)
#537    _RawViewElement.update (package:flutter/src/widgets/view.dart:552:5)
#538    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#539    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#540    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#541    StatelessElement.update (package:flutter/src/widgets/framework.dart:5707:5)
#542    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#543    ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5656:16)
#544    StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5794:11)
#545    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#546    StatefulElement.update (package:flutter/src/widgets/framework.dart:5817:5)
#547    Element.updateChild (package:flutter/src/widgets/framework.dart:3941:15)
#548    RootElement._rebuild (package:flutter/src/widgets/binding.dart:1636:16)
#549    RootElement.update (package:flutter/src/widgets/binding.dart:1614:5)
#550    RootElement.performRebuild (package:flutter/src/widgets/binding.dart:1628:7)
#551    Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
#552    BuildScope._tryRebuild (package:flutter/src/widgets/framework.dart:2694:15)
#553    BuildScope._flushDirtyElements (package:flutter/src/widgets/framework.dart:2753:11)
#554    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:3048:18)
#555    AutomatedTestWidgetsFlutterBinding.drawFrame (package:flutter_test/src/binding.dart:1428:19)
#556    RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:475:5)
#557    SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1397:15)
#558    SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1318:9)
#559    AutomatedTestWidgetsFlutterBinding.pump.<anonymous closure> (package:flutter_test/src/binding.dart:1283:9)
#562    TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:74:41)
#563    AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:1270:27)
#564    WidgetTester.pumpWidget.<anonymous closure> (package:flutter_test/src/widget_tester.dart:608:22)
#567    TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:74:41)
#568    WidgetTester.pumpWidget (package:flutter_test/src/widget_tester.dart:605:27)
#569    main.<anonymous closure> (file:///Users/malte/code/counter_app/test/widget_test.dart:16:18)
#570    testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:189:29)
<asynchronous suspension>
#571    TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:1027:5)
<asynchronous suspension>
<asynchronous suspension>
(elided 8 frames from dart:async and package:stack_trace)
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
A Timer is still pending even after the widget tree was disposed.
'package:flutter_test/src/binding.dart':
Failed assertion: line 1537 pos 12: '!timersPending'

When the exception was thrown, this was the stack:
#2      AutomatedTestWidgetsFlutterBinding._verifyInvariants (package:flutter_test/src/binding.dart:1537:12)
#3      TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:1044:7)
<asynchronous suspension>
<asynchronous suspension>
(elided 3 frames from class _AssertionError and package:stack_trace)

The test description was:
  Counter increments smoke test
════════════════════════════════════════════════════════════════════════════════════════════════════

Temporary Workaround

As a temporary workaround, I used this:

// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:counter_app/main.dart';

void main() {
  testWidgets('Counter increments smoke test', (WidgetTester tester) async {
    // Build our app and trigger a frame.
-    await tester.pumpWidget(const MyApp());
+    await tester.runAsync(() => tester.pumpWidget(const MyApp()));

    // Verify that our counter starts at 0.
    expect(find.text('0'), findsOneWidget);
    expect(find.text('1'), findsNothing);

    // Tap the '+' icon and trigger a frame.
    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();

    // Verify that our counter has incremented.
    expect(find.text('0'), findsNothing);
    expect(find.text('1'), findsOneWidget);
  });
}

Flutter Doctor output

Doctor output
[✓] Flutter (Channel stable, 3.27.3, on macOS 14.5 23F79 darwin-x64, locale en-CH)
    • Flutter version 3.27.3 on channel stable at /Users/private/.puro/envs/stable/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision c519ee916e (3 weeks ago), 2025-01-21 10:32:23 -0800
    • Engine revision e672b006cb
    • Dart version 3.6.1
    • DevTools version 2.40.2

[✓] Android toolchain - develop for Android devices (Android SDK version 35.0.1)
    • Android SDK at /Users/private/Library/Android/sdk
    • Platform android-35, build-tools 35.0.1
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 21.0.4+-12422083-b607.1)
    • All Android licenses accepted.

[✗] Xcode - develop for iOS and macOS
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS and macOS development.
      Download at: https://developer.apple.com/xcode/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
        sudo xcodebuild -runFirstLaunch
    ✗ CocoaPods not installed.
        CocoaPods is a package manager for iOS or macOS platform code.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/to/platform-plugins
      For installation instructions, see https://guides.cocoapods.org/using/getting-started.html#installation

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2024.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 21.0.4+-12422083-b607.1)

[✓] VS Code (version 1.95.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.102.0

[✓] Connected device (3 available)            
    • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 15 (API 35) (emulator)
    • macOS (desktop)              • macos         • darwin-x64     • macOS 14.5 23F79 darwin-x64
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 133.0.6943.54

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

Metadata

Metadata

Assignees

Labels

acceptedA valid and reproducible issuebugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions