Skip to content

AnimatedList throws 'itemIndex >= 0 && itemIndex < _itemsCount': is not true. when removing all items when an item is being removed #176362

Description

@Shunt22

Steps to reproduce

  1. Run provided code sample
  2. Press delete icon on any list item to start long delete animation
  3. While delete animation is running - press "Clear list" to remove all items from the list
  4. Observe exception.

Is this a bug or intended behaivour?
What stops me from clearing list?

Expected results

List should be cleared without errors

Actual results

It throws an error.

[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: 'package:flutter/src/widgets/animated_scroll_view.dart': Failed assertion: line 1398 pos 12: 'itemIndex >= 0 && itemIndex < _itemsCount': is not true.

Code sample

Code sample
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: AnimatedListExample(),
    );
  }
}

class AnimatedListExample extends StatefulWidget {
  const AnimatedListExample({super.key});

  @override
  State<AnimatedListExample> createState() => _AnimatedListExampleState();
}

class _AnimatedListExampleState extends State<AnimatedListExample> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  final List<int> _items = List.generate(10, (index) => index);

  void _removeItem(int index) {
    final removedItem = _items[index];
    _listKey.currentState?.removeItem(
      index,
      (context, animation) => SizeTransition(
        sizeFactor: animation,
        child: _buildItem(removedItem, animation, isRemoved: true),
      ),
      // 👇 Long delay so you can press "Remove All" while it’s still animating
      duration: const Duration(seconds: 10),
    );
    _items.removeAt(index);
  }

  void _removeAll() {
    _listKey.currentState?.removeAllItems(
      (context, animation) {
        return SizeTransition(
          sizeFactor: animation,
          child: Container(
            color: Colors.red[100],
            child: const ListTile(
              title: Text("Removing..."),
            ),
          ),
        );
      },
      duration: const Duration(seconds: 2),
    );
    _items.clear();
  }

  Widget _buildItem(int item, Animation<double> animation,
      {bool isRemoved = false}) {
    return SizeTransition(
      sizeFactor: animation,
      child: Card(
        margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
        child: ListTile(
          title: Text("Item $item"),
          trailing: !isRemoved
              ? IconButton(
                  icon: const Icon(Icons.delete, color: Colors.red),
                  onPressed: () {
                    final index = _items.indexOf(item);
                    if (index != -1) _removeItem(index);
                  },
                )
              : null,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("AnimatedList Example"),
        actions: [
          TextButton(
            child: Text("Clear list"),
         
            onPressed: _items.isNotEmpty ? _removeAll : null,
          )
        ],
      ),
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _items.length,
        itemBuilder: (context, index, animation) {
          return _buildItem(_items[index], animation);
        },
      ),
    );
  }
}

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
═══════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
'package:flutter/src/widgets/animated_scroll_view.dart': Failed assertion: line 1398 pos 12: 'itemIndex >= 0 && itemIndex < _itemsCount': is not true.

Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=02_bug.yml

When the exception was thrown, this was the stack:
#2      _SliverAnimatedMultiBoxAdaptorState.removeItem (package:flutter/src/widgets/animated_scroll_view.dart:1398:12)
animated_scroll_view.dart:1398
#3      _SliverAnimatedMultiBoxAdaptorState.removeAllItems (package:flutter/src/widgets/animated_scroll_view.dart:1443:7)
animated_scroll_view.dart:1443
#4      _AnimatedScrollViewState.removeAllItems (package:flutter/src/widgets/animated_scroll_view.dart:788:48)
animated_scroll_view.dart:788
#5      _AnimatedListExampleState._removeAll (package:bug/main.dart:43:28)
main.dart:43
#6      _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1204:21)
ink_well.dart:1204
#7      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:345:24)
recognizer.dart:345
#8      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:758:11)
tap.dart:758
#9      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:383:5)
tap.dart:383
#10     BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:314:7)
tap.dart:314
#11     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:721:9)
recognizer.dart:721
#12     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:97:12)
pointer_router.dart:97
#13     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:142:9)
pointer_router.dart:142
#14     _LinkedHashMapMixin.forEach (dart:_compact_hash:764:13)
#15     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:140:18)
pointer_router.dart:140
#16     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:130:7)
pointer_router.dart:130
#17     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:528:19)
binding.dart:528
#18     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:498:22)
binding.dart:498
#19     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:473:11)
binding.dart:473
#20     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:437:7)
binding.dart:437
#21     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:394:5)
binding.dart:394
#22     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:341:7)
binding.dart:341
#23     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:308:9)
binding.dart:308
#24     _invoke1 (dart:ui/hooks.dart:346:13)
hooks.dart:346
#25     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:467:7)
platform_dispatcher.dart:467
#26     _dispatchPointerDataPacket (dart:ui/hooks.dart:281:31)
hooks.dart:281
(elided 2 frames from class _AssertionError)

Handler: "onTap"
Recognizer: TapGestureRecognizer#7718a
    debugOwner: GestureDetector
    state: possible
    won arena
    finalPosition: Offset(1231.0, 32.0)
    finalLocalPosition: Offset(46.5, 20.0)
    button: 1
    sent tap down

Flutter Doctor output

Doctor output

Activity

  1. danagbemava-nc commented on Oct 2, 2025

    @danagbemava-nc
    Member

    Reproducible using the code sample provided above.

    This is likely working as intended but some documentation about the expectation would be ideal.

    Labeling for further insight.

    flutter doctor -v
    [✓] Flutter (Channel stable, 3.35.5, on macOS 26.1 25B5042k darwin-arm64, locale en-US) [606ms]
        • Flutter version 3.35.5 on channel stable at /Users/deanli/dev/stable
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision ac4e799d23 (6 days ago), 2025-09-26 12:05:09 -0700
        • Engine revision d3d45dcf25
        • Dart version 3.9.2
        • DevTools version 2.48.0
        • Feature flags: enable-web, enable-linux-desktop, enable-macos-desktop, enable-windows-desktop, enable-android, enable-ios, cli-animations, enable-lldb-debugging
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 36.1.0) [6.4s]
        • Android SDK at /Users/deanli/Library/Android/sdk
        • Emulator version 36.2.10.0 (build_id 14110321) (CL:N/A)
        • Platform android-36.1, build-tools 36.1.0
        • Java binary at: /Users/deanli/Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
          This is the JDK bundled with the latest Android Studio installation on this machine.
          To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
        • Java version OpenJDK Runtime Environment (build 21.0.8+-14018985-b1038.68)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 26.1) [1,377ms]
        • Xcode at /Applications/Xcode-26.1.0-beta.app/Contents/Developer
        • Build 17B5025f
        • CocoaPods version 1.16.2
    
    [✓] Chrome - develop for the web [7ms]
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2025.1) [6ms]
        • Android Studio at /Users/deanli/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.8+-14018985-b1038.68)
    
    [✓] VS Code (version 1.103.2) [5ms]
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.120.0
    
    [✓] Connected device (3 available) [7.2s]
        • iPhone 16 Pro Max (mobile) • 00008140-00194CC23A68801C • ios            • iOS 26.1 23B5044l
        • macOS (desktop)            • macos                     • darwin-arm64   • macOS 26.1 25B5042k darwin-arm64
        • Chrome (web)               • chrome                    • web-javascript • Google Chrome 140.0.7339.214
    
    [✓] Network resources [816ms]
        • All expected network resources are available.
    
    • No issues found!
    
    [!] Flutter (Channel master, 3.37.0-1.0.pre-380, on macOS 26.1 25B5042k darwin-arm64, locale en-US) [3.9s]
        • Flutter version 3.37.0-1.0.pre-380 on channel master at /Users/deanli/dev/master
        ! Warning: `flutter` on your path resolves to /Users/deanli/dev/stable/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/deanli/dev/master. Consider adding /Users/deanli/dev/master/bin to the front of your path.
        ! Warning: `dart` on your path resolves to /Users/deanli/dev/stable/bin/dart, which is not inside your current Flutter SDK checkout at /Users/deanli/dev/master. Consider adding /Users/deanli/dev/master/bin to the front of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 2bf5da46a5 (5 hours ago), 2025-10-02 00:24:31 -0400
        • Engine revision 2bf5da46a5
        • Dart version 3.10.0 (build 3.10.0-268.0.dev)
        • DevTools version 2.50.0
        • Feature flags: enable-web, enable-linux-desktop, enable-macos-desktop, enable-windows-desktop, enable-android, enable-ios, cli-animations, enable-native-assets, omit-legacy-version-file, enable-lldb-debugging
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 36.1.0) [1,381ms]
        • Android SDK at /Users/deanli/Library/Android/sdk
        • Emulator version 36.2.10.0 (build_id 14110321) (CL:N/A)
        • Platform android-36.1, build-tools 36.1.0
        • Java binary at: /Users/deanli/Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
          This is the JDK bundled with the latest Android Studio installation on this machine.
          To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
        • Java version OpenJDK Runtime Environment (build 21.0.8+-14018985-b1038.68)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 26.1) [994ms]
        • Xcode at /Applications/Xcode-26.1.0-beta.app/Contents/Developer
        • Build 17B5025f
        • CocoaPods version 1.16.2
    
    [✓] Chrome - develop for the web [6ms]
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Connected device (3 available) [6.2s]
        • iPhone 16 Pro Max (mobile) • 00008140-00194CC23A68801C • ios            • iOS 26.1 23B5044l
        • macOS (desktop)            • macos                     • darwin-arm64   • macOS 26.1 25B5042k darwin-arm64
        • Chrome (web)               • chrome                    • web-javascript • Google Chrome 140.0.7339.214
    
    [✓] Network resources [1,190ms]
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
    
  2. added
    frameworkflutter/packages/flutter repository. See also f: labels.
    f: scrollingViewports, list views, slivers, etc.
    a: error messageError messages from the Flutter framework
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    and removed
    in triagePresently being triaged by the triage team
    on Oct 2, 2025
  3. changed the title [-]AnimatedList items removal bug[/-] [+]AnimatedList throws `'itemIndex >= 0 && itemIndex < _itemsCount': is not true.` when removing all items when an item is being removed[/+] on Oct 2, 2025
  4. kazbeksultanov commented on Oct 3, 2025

    @kazbeksultanov
    Contributor

    @Shunt22 I created a fix for this issue, I don't know exactly what you expected, but I believe what I proposed should handle your case.

    @danagbemava-nc can you also take a look?

  5. Shunt22 commented on Oct 3, 2025

    @Shunt22
    Author

    @Shunt22 I created a fix for this issue, I don't know exactly what you expected, but I believe what I proposed should handle your case.

    @danagbemava-nc can you also take a look?

    Hi @kazbeksultanov , thanks! Looks good to me!

    Hi @danagbemava-nc ,

    Reproducible using the code sample provided above.

    This is likely working as intended but some documentation about the expectation would be ideal.

    Labeling for further insight.

    flutter doctor -v

    In my opinion user should be able to clear the list whenever. Why should he wait for the animation to finish..?
    If this was intended - there is no point in using AnimatedListView. I had to switch back to simple ListView with self-made animation.

  6. added
    P2Important issues not at the top of the work list
    on Oct 7, 2025
  7. added a commit that references this issue on Oct 21, 2025
    61fff25
  8. github-actions commented on Nov 5, 2025

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  9. locked as resolved and limited conversation to collaborators on Nov 5, 2025
  10. added
    r: fixedIssue is closed as already fixed in a newer version
    on Nov 7, 2025
  11. added a commit that references this issue on Dec 10, 2025
    61200ea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

P2Important issues not at the top of the work lista: error messageError messages from the Flutter frameworkf: scrollingViewports, list views, slivers, etc.found in release: 3.35Found to occur in 3.35found in release: 3.37Found to occur in 3.37frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onr: fixedIssue is closed as already fixed in a newer versionteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions