简体   繁体   中英

Flutter: SUPPRESS Exception “RenderBox was not laid out”

First of all, I know what causes this Exception.

I have a ListView with multiple Widgets in it, but I only want to display one and keep the others loaded.

It's working very well, but I keep getting the RenderBox Exception (Because of flex 0 i think) in the console which is distracating while debugging.

How can I surpress this Exception without, not-rendering the Widgets?

Widget build(BuildContext context) {
  int showPage = 0;
  return ListView(
    key: someKey,
    children: [
      Expanded(
        flex: showPage == 0 ? 1 : 0,
        child: CustomWidget1,
      ),
      Expanded(
        flex: showPage == 1 ? 1 : 0,
        child: CustomWidget2,
      ),
      Expanded(
        flex: showPage == 2 ? 1 : 0,
        child: CustomWidget3,
      ),
    ]
  );
}

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderCustomPaint#b7941 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE

'package:flutter/src/rendering/box.dart':
Failed assertion: line 1785 pos 12: 'hasSize'

The relevant error-causing widget was
ListView-[Null#007db]
════════════════════════════════════════════════════════════════════════════════

It is probably not a good idea to try to suppress that sort of error.

If you want to keep a Widget active (ie in the widget tree) but not visible, you can wrap it in an Offstage : https://api.flutter.dev/flutter/widgets/Offstage-class.html

A better solution is to use the IndexedStack widget (https://api.flutter.dev/flutter/widgets/IndexedStack-class.html ).

You can provide a list of widgets, and an index, an it will display only the selected item, eg:

IndexedStack(
   children: [Widget1(), Widget2()],
   index: 0,
)  // displays Widget1()


IndexedStack(
   children: [Widget1(), Widget2()],
   index: 1,
)  // displays Widget2()

All the children will remain loaded and their state will be kept alive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM