Skip to content

Crash when using SliverGrid, findChildIndexCallback, a sparsely populated grid and updating the children #138749

Closed

Description

@dowski

Is there an existing issue for this?

Steps to reproduce

In the app I'm working on, we have a custom SliverGrid layout. It does a somewhat sparse layout of grid items, with a contiguous series of items and other items interspersed along the way. Some actions performed in the app causes the grid contents to be limited - thus items are removed from the grid.

We also use a findChildIndexCallback with SliverChildBuilderDelegate. It seems like that combination can lead to places in the grid where removing items leads to a crash.

  1. Open https://dartpad.dev/?id=d9f723468f22d4035dfcf90366802151
  2. Run app
  3. Scroll down until "grid item 7" just scrolls into view in the left column
  4. Press the FAB/refresh button in the bottom right

Expected results

No crashes or issues.

Actual results

══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
The following assertion was thrown during performLayout():
Assertion failed:
file:///opt/flutter/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart:508:12
childCount >= leadingGarbage + trailingGarbage
is not true

Widget creation tracking is currently disabled. Enabling it enables improved error messages. It can
be enabled by passing `--track-widget-creation` to `flutter run` or `flutter test`.

When the exception was thrown, this was the stack

The following RenderObject was being processed when the exception was fired: RenderSliverGrid#255ad relayoutBoundary=up1 NEEDS-LAYOUT NEEDS-COMPOSITING-BITS-UPDATE:
  needs compositing
  creator: SliverGrid ← Viewport ← IgnorePointer-[GlobalKey#e6cb3] ← Semantics ← Listener ←
    _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#04dfe] ←
    Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#8e450] ←
    NotificationListener<ScrollMetricsNotification> ← RepaintBoundary ← ⋯
  parentData: paintOffset=Offset(0.0, 0.0) (can use size)
  constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle,
    scrollOffset: 6878.2, remainingPaintExtent: 805.0, crossAxisExtent: 826.0, crossAxisDirection:
    AxisDirection.right, viewportMainAxisExtent: 805.0, remainingCacheExtent: 1305.0, cacheOrigin:
    -250.0)
  geometry: SliverGeometry(scrollExtent: 21000.0, paintExtent: 805.0, maxPaintExtent: 21000.0,
    hasVisualOverflow: true, cacheExtent: 1305.0)
  currently live children: 1 to 6
This RenderObject had the following descendants (showing up to depth 5):
    child with index 1: RenderIndexedSemantics#9f23a
      child: RenderRepaintBoundary#89623 NEEDS-PAINT
        child: _RenderColoredBox#da96c NEEDS-PAINT
          child: RenderPositionedBox#60e7f NEEDS-LAYOUT
            child: RenderParagraph#3e200 relayoutBoundary=up1 NEEDS-LAYOUT
    child with index 2: RenderIndexedSemantics#cd9d3
      child: RenderRepaintBoundary#04b11 NEEDS-PAINT
        child: _RenderColoredBox#d3dc9 NEEDS-PAINT
          child: RenderPositionedBox#d0f81 NEEDS-LAYOUT
            child: RenderParagraph#6065a relayoutBoundary=up1 NEEDS-LAYOUT
    child with index 5: RenderIndexedSemantics#5f68d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
      child: RenderRepaintBoundary#ed0b9 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
        child: _RenderColoredBox#b737d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
          child: RenderPositionedBox#2daac NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
            child: RenderParagraph#26a3e NEEDS-LAYOUT NEEDS-PAINT
    child with index 6: RenderIndexedSemantics#4b2f1 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
      child: RenderRepaintBoundary#93339 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
        child: _RenderColoredBox#10147 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
          child: RenderPositionedBox#a9025 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
            child: RenderParagraph#23002 NEEDS-LAYOUT NEEDS-PAINT
════════════════════════════════════════════════════════════════════════════════════════════════════

Code sample

Code sample

See https://dartpad.dev/?id=d9f723468f22d4035dfcf90366802151.

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[Paste your output here]

Activity

  1. danagbemava-nc commented on Nov 21, 2023

    @danagbemava-nc
    Member

    Reproducible using the code sample shared above.

    Tested on 3.13, 3.16 & 3.17.0-12.0.pre.39

    Labeling for further insight.

    code sample (pasted for convenience)
    import 'dart:math';
    import 'package:flutter/material.dart';
    import 'package:flutter/src/rendering/sliver.dart';
    import 'package:flutter/src/rendering/sliver_grid.dart';
    import 'package:collection/collection.dart';
    
    
    /// Demo for a Flutter bug.
    ///
    /// ## Instructions
    /// 1. Run app
    /// 2. Scroll down until "grid item 7" just scrolls into view in the left column
    /// 3. Press the FAB/refresh button in the bottom right
    ///
    /// In the console, you'll see something like:
    ///
    /// ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
    /// The following assertion was thrown during performLayout():
    /// Assertion failed:
    /// file:///opt/flutter/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart:508:12
    /// childCount >= leadingGarbage + trailingGarbage
    /// is not true
    ///
    /// If you remove the `findChildIndexCallback` from the `SliverChildBuilderDelegate` the crash
    /// is not triggered.
    
    void main() => runApp(const CustomScrollViewExampleApp());
    
    class CustomScrollViewExampleApp extends StatelessWidget {
      const CustomScrollViewExampleApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: CustomScrollViewExample(),
        );
      }
    }
    
    class CustomScrollViewExample extends StatefulWidget {
      const CustomScrollViewExample({super.key});
    
      @override
      State<CustomScrollViewExample> createState() =>
          _CustomScrollViewExampleState();
    }
    
    class _CustomScrollViewExampleState extends State<CustomScrollViewExample> {
      late final List<MyCollection> _initialCollections;
      late List<MyCollection> _activeCollections;
      late List<ValueKey<String>> _activeItemKeys;
      var _hideBadgesAndChildren = false;
    
      @override
      void initState() {
        super.initState();
        _initialCollections = [
          MyCollection(2),
          MyCollection(1),
          MyCollection(0),
          MyCollection(1),
          MyCollection(2),
          MyCollection(0),
          MyCollection(0),
        ];
        _refreshActiveCollections();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Bug demo'),
          ),
          body: _activeCollections.isNotEmpty
              ? CustomScrollView(
                  slivers: <Widget>[
                    SliverGrid(
                      gridDelegate: MyGridDelegate(_activeCollections),
                      delegate: SliverChildBuilderDelegate(
                        (BuildContext context, int index) {
                          return Container(
                            key: _activeItemKeys[index],
                            alignment: Alignment.center,
                            color: Colors.teal[100 * (index % 9)],
                            child: Text('grid item $index'),
                          );
                        },
                        childCount: _activeCollections.length +
                            _activeCollections.map((c) => c.childCount).sum,
                        // Comment out this findChildIndexCallback and the
                        // associated test passes ...
                        findChildIndexCallback: (key) {
                          final potentialIndex =
                              _activeItemKeys.indexOf(key as ValueKey<String>);
                          if (potentialIndex > 0) {
                            return potentialIndex;
                          }
                          return null;
                        },
                      ),
                    ),
                  ],
                )
              : Container(),
          floatingActionButton: FloatingActionButton(
              child: const Icon(Icons.refresh_rounded),
              // Toggle children and badges on and off.
              onPressed: () {
                setState(() {
                  _hideBadgesAndChildren = !_hideBadgesAndChildren;
                  _refreshActiveCollections();
                });
              }),
        );
      }
    
      void _refreshActiveCollections() {
        _activeCollections = [];
        for (final c in _initialCollections) {
          c.hideChildren = _hideBadgesAndChildren;
          _activeCollections.add(c);
          if (!_hideBadgesAndChildren && _initialCollections.last != c) {
            _activeCollections.add(MyCollection.badge());
          }
        }
        _assignItemKeys();
      }
    
      /// The generated [_activeItemKeys] are used in the findChildIndexCallback and
      /// when building child widgets.
      ///
      /// Should be called whenever the list of [_activeCollections] changes.
      void _assignItemKeys() {
        _activeItemKeys = [];
        var badgeIndex = 0;
        var collectionIndex = 0;
        for (final collection in _activeCollections) {
          if (collection.isBadge) {
            _activeItemKeys.add(ValueKey('badge $badgeIndex'));
            badgeIndex++;
          } else {
            _activeItemKeys.add(ValueKey('collection $collectionIndex'));
            for (var i = 0; i < collection.childCount; i++) {
              _activeItemKeys
                  .add(ValueKey('collection $collectionIndex, child $i'));
            }
            collectionIndex++;
          }
        }
      }
    }
    
    class MyGridDelegate implements SliverGridDelegate {
      final List<MyCollection> _collections;
    
      MyGridDelegate(this._collections);
    
      @override
      SliverGridLayout getLayout(SliverConstraints constraints) {
        final childWidth = constraints.asBoxConstraints().maxWidth / 3;
        const maxChildHeight = 200.0;
        const collectionHeight = 3000.0;
        return MyGridLayout(
            _collections, childWidth, maxChildHeight, collectionHeight);
      }
    
      @override
      bool shouldRelayout(covariant MyGridDelegate oldDelegate) {
        final result = oldDelegate._collections != _collections;
        return result;
      }
    }
    
    /// Defines the layout that helps reproduce this bug.
    ///
    /// [MyCollection] instances are laid out vertically and their children can
    /// start being rendered at half their height. The overall height of the layout
    /// is defined by the summed height of the collections.
    ///
    /// [MyCollection.badge] instances render over/between other collections. They
    /// don't contribute toward the height.
    ///
    /// Here is a simple diagram that shows a layout of a a collection, its two
    /// children, a badge and then the start of another collection.
    ///
    ///     +----+
    ///     |    |
    ///     |    |
    ///     |    |----+----+
    ///     |    |    |    |
    ///     |    |----+----+
    ///     |    |
    ///     |    |
    ///     | +----------+
    ///     +-|          |
    ///     | +----------+
    ///     |    |
    ///     ......
    class MyGridLayout implements SliverGridLayout {
      final double _childWidth;
      final double _childHeight;
      final double _collectionHeight;
    
      final List<MyCollection> _collections;
    
      MyGridLayout(this._collections, this._childWidth, double maxChildHeight,
          this._collectionHeight)
          : _childHeight = maxChildHeight;
    
      @override
      double computeMaxScrollOffset(int childCount) {
        return _collections.map((c) => c.isBadge ? 0.0 : _collectionHeight).sum;
      }
    
      @override
      SliverGridGeometry getGeometryForChildIndex(int index) {
        var consumed = 0;
        var scrollOffset = 0.0;
        assert(_collections.isNotEmpty);
        for (final collection in _collections) {
          if (index == consumed++) {
            if (collection.isBadge) {
              return _badgeGeometry(collection, scrollOffset);
            } else {
              return _headerGeometry(collection, scrollOffset);
            }
          }
          if (consumed + collection.childCount > index) {
            final childIndex = index - consumed;
            return _childGeometry(childIndex, scrollOffset, _childHeight);
          }
          consumed += collection.childCount;
          scrollOffset += collection.isBadge ? 0 : _collectionHeight;
        }
        throw StateError("can't get geometry for index $index");
      }
    
      @override
      int getMaxChildIndexForScrollOffset(double scrollOffset) {
        var consumed = 0.0;
        var index = -1;
        for (final collection in _collections) {
          // Increment for the collection.
          index++;
          consumed += collection.isBadge ? 0 : _collectionHeight / 2;
          // The children can appear starting at halfway down the parent height.
          // First check if the scrollOffset is earlier than that.
          if (scrollOffset <= consumed) {
            return index;
          }
    
          var consumedByChildren = 0.0;
          for (var availableChildren = collection.childCount;
              availableChildren > 0;
              availableChildren -= 2) {
            consumedByChildren += _childHeight;
            index += min(2, availableChildren);
            if (scrollOffset <= consumed + consumedByChildren) {
              return index;
            }
          }
    
          final height = collection.isBadge ? 0 : _collectionHeight;
          if (consumedByChildren < height) {
            consumed += height / 2; // - consumedByChildren;
          }
          if (scrollOffset <= consumed) {
            return index;
          }
        }
        return index;
      }
    
      @override
      int getMinChildIndexForScrollOffset(double scrollOffset) {
        var consumed = 0.0;
        var index = -1;
        for (final collection in _collections) {
          index++;
          consumed += collection.isBadge ? 0 : _collectionHeight;
          if (scrollOffset <= consumed) {
            return index;
          }
        }
        return 0;
      }
    
      SliverGridGeometry _headerGeometry(
          MyCollection collection, double scrollOffset) {
        return SliverGridGeometry(
            crossAxisOffset: 0,
            crossAxisExtent: _childWidth,
            mainAxisExtent: _collectionHeight,
            scrollOffset: scrollOffset);
      }
    
      SliverGridGeometry _badgeGeometry(
          MyCollection collection, double scrollOffset) {
        return SliverGridGeometry(
            crossAxisOffset: 50,
            crossAxisExtent: _childWidth * 3 - 100,
            mainAxisExtent: 50,
            scrollOffset: scrollOffset - 25);
      }
    
      SliverGridGeometry _childGeometry(
          int childIndex, double scrollOffset, double childHeight) {
        final columnIndex = childIndex % 2;
        final rowIndex = childIndex ~/ 2;
        return SliverGridGeometry(
            crossAxisOffset: _childWidth + _childWidth * columnIndex,
            crossAxisExtent: _childWidth,
            mainAxisExtent: childHeight,
            scrollOffset:
                scrollOffset + rowIndex * childHeight + _collectionHeight / 2);
      }
    }
    
    /// Represents either a collection with a number of children or a "badge" that
    /// is shown between/over other collections.
    class MyCollection {
      final int _childCount;
      final bool isBadge;
      bool hideChildren = false;
    
      MyCollection(this._childCount) : isBadge = false;
    
      MyCollection.badge()
          : _childCount = 0,
            isBadge = true;
    
      int get childCount {
        if (isBadge || hideChildren) {
          return 0;
        } else {
          return _childCount;
        }
      }
    
      @override
      String toString() => isBadge
          ? 'MyCollection.badge()'
          : 'MyCollection(childCount: $childCount)';
    }
    flutter doctor -v
    [!] Flutter (Channel stable, 3.16.0, on macOS 14.1.1 23B81 darwin-arm64, locale en-GB)
        • Flutter version 3.16.0 on channel stable at /Users/nexus/dev/sdks/flutter
        ! Warning: `flutter` on your path resolves to /Users/nexus/dev/sdks/flutters/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/nexus/dev/sdks/flutter. Consider adding /Users/nexus/dev/sdks/flutter/bin to the front of your path.
        ! Warning: `dart` on your path resolves to /Users/nexus/dev/sdks/flutters/bin/dart, which is not inside your current Flutter SDK checkout at /Users/nexus/dev/sdks/flutter. Consider adding /Users/nexus/dev/sdks/flutter/bin to the front of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision db7ef5bf9f (6 days ago), 2023-11-15 11:25:44 -0800
        • Engine revision 74d16627b9
        • Dart version 3.2.0
        • DevTools version 2.28.2
        • 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 34.0.0-rc1)
        • Android SDK at /Users/nexus/Library/Android/sdk
        • Platform android-34, build-tools 34.0.0-rc1
        • Java binary at: /Users/nexus/Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 15.0)
        • Xcode at /Applications/Xcode-15.0.0-Release.Candidate.app/Contents/Developer
        • Build 15A240d
        • CocoaPods version 1.13.0
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.3)
        • Android Studio at /Users/nexus/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 17.0.6+0-17.0.6b829.9-10027231)
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.2.5)
        • IntelliJ at /Users/nexus/Applications/IntelliJ IDEA Ultimate.app
        • Flutter plugin version 76.3.4
        • Dart plugin version 232.10072.19
    
    [✓] VS Code (version 1.84.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.76.0
    
    [✓] Connected device (4 available)
        • Nexus (mobile)       • 00008020-001875E83A38002E • ios            • iOS 17.1.1 21B91
        • Dean’s iPad (mobile) • 00008103-000825C811E3401E • ios            • iOS 17.1 21B74
        • macOS (desktop)      • macos                     • darwin-arm64   • macOS 14.1.1 23B81 darwin-arm64
        • Chrome (web)         • chrome                    • web-javascript • Google Chrome 119.0.6045.159
    
    [✓] Network resources
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
    
    [✓] Flutter (Channel master, 3.17.0-12.0.pre.39, on macOS 14.1.1 23B81 darwin-arm64, locale en-GB)
        • Flutter version 3.17.0-12.0.pre.39 on channel master at /Users/nexus/dev/sdks/flutters
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision b6ef78e955 (6 hours ago), 2023-11-20 23:37:25 -0500
        • Engine revision 70b1c73412
        • Dart version 3.3.0 (build 3.3.0-152.0.dev)
        • DevTools version 2.30.0-dev.4
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0-rc1)
        • Android SDK at /Users/nexus/Library/Android/sdk
        • Platform android-34, build-tools 34.0.0-rc1
        • Java binary at: /Users/nexus/Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 15.0)
        • Xcode at /Applications/Xcode-15.0.0-Release.Candidate.app/Contents/Developer
        • Build 15A240d
        • CocoaPods version 1.13.0
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.3)
        • Android Studio at /Users/nexus/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 17.0.6+0-17.0.6b829.9-10027231)
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2023.2.5)
        • IntelliJ at /Users/nexus/Applications/IntelliJ IDEA Ultimate.app
        • Flutter plugin version 76.3.4
        • Dart plugin version 232.10072.19
    
    [✓] VS Code (version 1.84.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.76.0
    
    [✓] Connected device (4 available)
        • Nexus (mobile)       • 00008020-001875E83A38002E • ios            • iOS 17.1.1 21B91
        • Dean’s iPad (mobile) • 00008103-000825C811E3401E • ios            • iOS 17.1 21B74
        • macOS (desktop)      • macos                     • darwin-arm64   • macOS 14.1.1 23B81 darwin-arm64
        • Chrome (web)         • chrome                    • web-javascript • Google Chrome 119.0.6045.159
    
    [✓] Network resources
        • All expected network resources are available.
    
    • No issues found!
    
  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 Nov 21, 2023
  3. added
    P0Critical issues such as a build break or regression
    on Nov 21, 2023
  4. xster commented on Nov 21, 2023

    @xster
    Member

    b/312248242 upstream

  5. goderbauer commented on Nov 21, 2023

    @goderbauer
    Member
  6. added
    P1High-priority issues at the top of the work list
    P0Critical issues such as a build break or regression
    and removed
    P0Critical issues such as a build break or regression
    P1High-priority issues at the top of the work list
    on Nov 21, 2023
  7. Piinks commented on Nov 22, 2023

    @Piinks
    Contributor

    Not sure where the issue is yet, but here is what I have found so far.

    When I run the repro, I see grid item 2 is a small box towards the top. If I comment out findChildIndexCallback to see what happens without a crash, and push the button, grid item 2 becomes a different widget, it is a large box further down the list. Additionally, grid item 2 is being assigned different keys when this change happens.
    When it crashes instead, the custom grid layout from the customer code is determining that only index 2 needs to be laid out, and that children up to index 1 and after index 4 need to be disposed, but that seems like the wrong indices since it omits index 3. 🤔

    Restoring findChildIndexCallback means that the SliverMultiBoxAdaptorElement._childElements are manipulated during performRebuild. Looking at this in the crash/no-crash scenario, it looks like the childCount used in RenderSliverGrid.performLayout is not being updated when the child elements are manipulated. The childCount is what is firing the assertion and causing the crash.

    In the no-crash scenario it plays out like this:

    // Before pressing button
    in RenderSliverGrid.performLayout
      grid layout says indices 4-7 should be laid out, childCount is 4
      Nothing to garbage collect.
    
    // Button pressed!
    at the end of SliverMultiBoxAdaptorElement.performRebuild (called 4 times with same result)
      _childElements.length is 4
    next in RenderSliverGrid.performLayout
      grid layout says indices 2-2 should be laid out, childCount is 3
      Garbage is collected for up to index 0 and >= index 3 (still seems off in the no crash case)
    

    Compared to the crashing scenario:

    // Before pressing button
    in RenderSliverGrid.performLayout
      grid layout says indices 4-7 should be laid out, childCount is 4
      Nothing to garbage collect.
    
    // Button pressed!
    at the end of SliverMultiBoxAdaptorElement.performRebuild (called 3 times with same result)
      _childElements.length is 3
    at the end of SliverMultiBoxAdaptorElement.performRebuild (called once more with new result)
      _childElements.length is 2
    next in RenderSliverGrid.performLayout
      grid layout says indices 2-2 should be laid out, childCount is 4
      Garbage is collected for up to index 1 and >= index 4 
    

    Other bits:

    In RenderSliverGrid.performLayout, the childCount as well as the first and last indices of the prior layout pass are used to determine garbage collection along with the new first and last index provided by the SliverGridLayout (which is a custom one in the OP). It could be that RenderSliverGrid is not doing a good job of supporting children being removed and inserted like in this case.

    This is what I have found so far, I will be out from here through the holiday. Passing it on to @chunhtai in case he discovers something while I am out!

  8. chunhtai commented on Nov 22, 2023

    @chunhtai
    Contributor

    I found the root cause, in SliverGrid.performLayout, we assume the children's indices are continuous, but that is not true when you remove child in the middle during a rebuild.

    I will put up a fix shortly

  9. github-actions commented on Dec 8, 2023

    @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.

  10. locked as resolved and limited conversation to collaborators on Dec 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

P0Critical issues such as a build break or regressiona: error messageError messages from the Flutter frameworkf: scrollingViewports, list views, slivers, etc.found in release: 3.16Found to occur in 3.16found in release: 3.17Found to occur in 3.17frameworkflutter/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