Skip to content

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

@Shunt22

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

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