Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

dart - 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]
════════════════════════════════════════════════════════════════════════════════

question from:https://stackoverflow.com/questions/65601596/flutter-suppress-exception-renderbox-was-not-laid-out

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

If you want to keep a Widget active (i.e. 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, e.g.:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...