When I call ListView.builder in FutureBuilder, always crashes

Issue

I’m using cloud_firestore, and trying to show the list of user information.
When I call ListView.builder in FutureBuilder, all the time it crashes.

List<dynamic> infoList = <dynamic>[];

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: originAppBar(context, pageNames.discovery),
        body: Center(
          child: FutureBuilder<DocumentSnapshot>(
            future: FirebaseFirestore.instance
                .collection("users")
                .doc(FirebaseAuth.instance.currentUser!.uid)
                .get(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasData && snapshot.data!.exists) {
                return ListView.builder(
                    shrinkWrap: true,
                    itemCount: infoList.length,
                    scrollDirection: Axis.horizontal,
                    itemBuilder: (BuildContext context, int index) {
                      return Text(infoList[index]);
                    });
              }

              return const Center(child: LinearProgressIndicator());
            },
          ),
        ));
  }

I checked that the data was acquired correctly. in this way;

if (snapshot.hasData && snapshot.data!.exists) {
    for (int i = 0; i < infoList; i++) {
        print(infoList[i].ToString());
    }
}

This print() shows strings correctly.

There error displayed;

════════ Exception caught by rendering library ═════════════════════════════════
The following assertion was thrown during performResize():
Horizontal viewport was given unbounded height.

Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
When the exception was thrown, this was the stack
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49  throw_
packages/flutter/src/rendering/viewport.dart 1424:15                                                                       <fn>
packages/flutter/src/rendering/viewport.dart 1435:14                                                                       computeDryLayout
packages/flutter/src/rendering/box.dart 2331:12                                                                            performResize
packages/flutter/src/rendering/object.dart 1837:9                                                                          layout
packages/flutter/src/rendering/proxy_box.dart 116:7                                                                        performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/proxy_box.dart 116:7                                                                        performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/proxy_box.dart 116:7                                                                        performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/proxy_box.dart 116:7                                                                        performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/proxy_box.dart 116:7                                                                        performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/proxy_box.dart 116:7                                                                        performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/layout_helper.dart 56:10                                                                    layoutChild
packages/flutter/src/rendering/flex.dart 829:43                                                                            [_computeSizes]
packages/flutter/src/rendering/flex.dart 931:32                                                                            performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/shifted_box.dart 437:7                                                                      performLayout
packages/flutter/src/rendering/object.dart 1858:7                                                                          layout
packages/flutter/src/rendering/custom_layout.dart 171:10                                                                   layoutChild
packages/flutter/src/material/scaffold.dart 1097:7                                                                         performLayout
packages/flutter/src/rendering/custom_layout.dart 240:7                                                                    [_callPerformLayout]
packages/flutter/src/rendering/custom_layout.dart 404:14                                                                   performLayout
packages/flutter/src/rendering/object.dart 1713:7                                                                          [_layoutWithoutResize]
packages/flutter/src/rendering/object.dart 885:17                                                                          flushLayout
packages/flutter/src/rendering/binding.dart 453:19                                                                         drawFrame
packages/flutter/src/widgets/binding.dart 883:13                                                                           drawFrame
packages/flutter/src/rendering/binding.dart 319:5                                                                          [_handlePersistentFrameCallback]
packages/flutter/src/scheduler/binding.dart 1143:15                                                                        [_invokeFrameCallback]
packages/flutter/src/scheduler/binding.dart 1080:9                                                                         handleDrawFrame
packages/flutter/src/scheduler/binding.dart 996:5                                                                          [_handleDrawFrame]
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 1003:13           invoke
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 157:5             invokeOnDrawFrame
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine.dart 440:45                                <fn>
The following RenderObject was being processed when the exception was fired: RenderViewport#5d88f NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
RenderObject: RenderViewport#5d88f NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    needs compositing
    parentData: <none> (can use size)
    constraints: BoxConstraints(0.0<=w<=1536.0, 0.0<=h<=Infinity)
    size: MISSING
    axisDirection: right
    crossAxisDirection: down
    offset: ScrollPositionWithSingleContext#747a0(offset: 0.0, range: null..null, viewport: null, ScrollableState, ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#220b1, ScrollDirection.idle)
    anchor: 0.0
    center child: RenderSliverPadding#d7763 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
        parentData: paintOffset=Offset(0.0, 0.0)
        constraints: MISSING
        geometry: null
        padding: EdgeInsets.zero
        textDirection: ltr
        child: RenderSliverList#e6b26 NEEDS-LAYOUT NEEDS-PAINT
            parentData: paintOffset=Offset(0.0, 0.0)
            constraints: MISSING
            geometry: null
            no children current live
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderViewport#5d88f NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderViewport#5d88f NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderIgnorePointer#e49f5 relayoutBoundary=up8 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderSemanticsAnnotations#2b185 relayoutBoundary=up7 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderPointerListener#7224c relayoutBoundary=up6 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderSemanticsGestureHandler#62790 relayoutBoundary=up5 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderPointerListener#ef0e5 relayoutBoundary=up4 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: _RenderScrollSemantics#d53de relayoutBoundary=up3 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE"

The relevant error-causing widget was
Column Column:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:18:20
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Assertion failed:
hasSize
"RenderBox was not laid out: RenderViewport#5d88f NEEDS-PAINT"

The relevant error-causing widget was
ListView ListView:file:///D:/FlutterProjects/TestProject/lib/discovery.dart:27:35
════════════════════════════════════════════════════════════════════════════════

Does anyone know a solution?

Thank you.

Addtional

Finally, this code works good!
I’ll write final code here for future me and who annoyed with this issue.

List<dynamic> infoList = <dynamic>[];

body: Center(
          child: FutureBuilder<DocumentSnapshot>(
            future: FirebaseFirestore.instance
                .collection("users")
                .doc(FirebaseAuth.instance.currentUser!.uid)
                .get(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasData && snapshot.data!.exists) {
                Map<String, dynamic> data =
                    snapshot.data!.data() as Map<String, dynamic>;
                infoList = data["info"];
                return ListView.builder(
                    shrinkWrap: true,
                    itemCount: infoList.length,
                    scrollDirection: Axis.horizontal,
                    itemBuilder: (BuildContext context, int index) {
                      return Text(infoList[index]);
                    });
              }

              return const Center(child: LinearProgressIndicator());
            },
          ),
        )

Solution

Add shrinkWrap: true, in ListView.builder.

As your listview is not bounded, flutter can’t understand how much space it will render, to bound it, you can use a Sizedbox or Container with height.
But it raised another problem, it can be scrollable or again renderbox overflowed error!
So the best way is using shrinkWrap in ListView.builder To use the listview as a dynamic widget.

body: Center(
          child: Column(
          children: [
            FutureBuilder<DocumentSnapshot>(
              future: FirebaseFirestore.instance
                  .collection("users")
                  .doc(FirebaseAuth.instance.currentUser!.uid)
                  .get(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                print(snapshot.data!.exists);
                if (snapshot.hasData && snapshot.data!.exists) {
                   return ListView.builder(
                      shrinkWrap: true, // here this is
                      itemCount: infoList.length,
                      scrollDirection: Axis.horizontal,
                      itemBuilder: (BuildContext context, int index) {
                        return Text(infoList[index].ToString());
                      });
                }

                return const Center(child: LinearProgressIndicator());
              },
            ),
          ],
        ))

Answered By – xahid_rocks

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *