Flutter: “ RenderFlex 子元素具有非零的 Flex,但是传入的高度约束是无限的”

我想有一个 ListView内的另一个小部件时,我在一个 Column包装 FutureBuilder,以便有一个简单的 Row。我得到了这个错误:

The following assertion was thrown during performLayout():
I/flutter (13816): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter (13816): When a column is in a parent that does not provide a finite height constraint, for example, if it is
I/flutter (13816): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter (13816): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter (13816): space in the vertical direction.
I/flutter (13816): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter (13816): cannot simultaneously expand to fit its parent.
I/flutter (13816): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter (13816): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter (13816): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter (13816): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter (13816): constraints provided by the parent.
I/flutter (13816): If this message did not help you determine the problem, consider using debugDumpRenderTree():

我的代码:

class ActivityShowTicketReplies extends StatefulWidget {
final Map<String, dynamic> ticketData;


ActivityShowTicketReplies({@required this.ticketData});


@override
State<StatefulWidget> createState() => ActivityShowTicketRepliesState();
}


class ActivityShowTicketRepliesState extends State<ActivityShowTicketReplies> {
TicketsTableData get _ticket => TicketsTableData.fromJson(json.decode(widget.ticketData.values.toList()[0][0].toString()));


@override
Widget build(BuildContext context) {
return ScopedModel(
model: CounterModel(),
child: Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0),
child: RaisedButton(
color: Colors.indigo,
onPressed: () => BlocProvider.of<AppPagesBloc>(context).dispatch(FragmentNavigateEvent(routeName: FRAGMENT_NEW_TICKET)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50.0)),
child: Container(
child: Text(
'new ticket',
style: AppTheme(context).caption().copyWith(color: Colors.white),
),
),
),
),
],
),
FutureBuilder(
future: Provider.of<TicketRepliesTableDao>(context).find(ticketId: _ticket.id),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
final List<TicketRepliesTableData> ticketReplies = snapshot.data;
if (ticketReplies.isNotEmpty) {
return Column(
children: <Widget>[
Card(
clipBehavior: Clip.antiAlias,
color: Colors.grey[50],
margin: EdgeInsets.all(10.0),
child: InkWell(
child: Stack(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 12.0),
child: ListTile(
title: Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Text(
'subject',
style: AppTheme(context).caption().copyWith(fontFamily: 'ShabnamBold'),
),
),
subtitle: Text(
_ticket.subject,
style: AppTheme(context).caption(),
),
),
),
Container(
height: 30.0,
margin: EdgeInsets.zero,
width: double.infinity,
color: Colors.grey[200],
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
                                              

],
),
),
],
),
Align(
alignment: Alignment.topLeft,
child: Container(
margin: EdgeInsets.only(top: 10.0),
constraints: BoxConstraints(
minWidth: 70.0,
),
height: 20.0,
width: 70.0,
decoration: BoxDecoration(
color: Colors.green[200],
borderRadius: BorderRadius.only(
topRight: Radius.circular(5.0),
bottomRight: Radius.circular(5.0),
)),
child: Center(
child: Text(
'status',
style: AppTheme(context).overLine().copyWith(fontFamily: 'ShabnamBold', color: Colors.black),
),
)),
),
],
),
onTap: () {},
),
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return Card(
clipBehavior: Clip.antiAlias,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text(
ticketReplies[index].createdAt,
style: AppTheme(context).caption().copyWith(fontFamily: 'ShabnamLight'),
),
],
),
ListTile(
title: Text(ticketReplies[index].reply),
),
],
),
),
);
},
itemCount: ticketReplies.length,
),
),
],
);
} else {
return Center(
child: Text(
'there isn't any reply message',
style: AppTheme(context).caption(),
),
);
}
} else {
return _loader(context, 'no reply');
}
} else
return _loader(context, Strings.pleaseWait);
},
),
],
),
),
),
);
}


Widget _loader(BuildContext context,String message) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ColorLoader3(
radius: 25.0,
dotRadius: 5.0,
),
Padding(
padding: const EdgeInsets.all(3.0),
child: Text(
Strings.pleaseWait,
style: AppTheme(context).caption().copyWith(color: Colors.red[900]),
),
),
],
));
}
}
154415 次浏览

Wrap your Column inside an Expanded or SizedBox (with some height) like this:

Expanded(
child: Column(...)
)

OR

SizedBox(
height: 200, // Some height
child: Column(...),
)

Note that a Flex class or sub-class (like Column) should not be child of other Flex classes, and their parent class needs to be of type Flexible (i.e. inherit it, like Expanded), else, Flex-class gets unbounded (and remaining space cannot be calculated) which causes no direct issue till yet another child tries to calculate and/or fill space.

This approach never fails me:

Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus finibus luctus tortor id pulvinar. Donec sollicitudin, dui vitae aliquam tristique, eros risus commodo enim, eget lobortis arcu velit ac arcu. "),
Text("Nunc tristique, ex ut volutpat feugiat, nulla nibh iaculis lectus, laoreet auctor justo tellus quis mi. Praesent ut interdum sem. Donec eget finibus augue, et vehicula elit. Praesent eu euismod arcu, eu maximus tellus. Ut diam est, sodales nec enim a, pharetra lobortis erat."),
]
)
)

I want to offer up another solution seeing that I just had to overcome this problem myself. For context, this is the over-simplified structure for the widget that was throwing this error:

Container
child: Column
children: Column, Spacer, Row

In my case, I wanted the Container to expand with the content that is inside of it. Initially, I defined a height and width for this container, but because I wanted it to dynamically expand, I removed those constraints. The error was then raised:

“RenderFlex children have non-zero flex but incoming height constraints are unbounded”

My problem was the Spacer in between the rows. The children of the first Column are trying to expand indefinitely (hence "non-zero flex") because the Spacer was pushing each child to the vertical bounds of its parent. This isn't usually a problem, but there are no bounds on the parent for the spacer to push the children to. This is because their parent, the first Column, was also trying to expand because the Container was not given a height or width property.

My fix was to simply replace the Spacer with a SizedBox that has a finite height:

Container
child: Column
children: Column, SizedBox(height: 10), Row

If you want to solve Render Flex issue, try:

Scaffold(
body: SingleChildScrollView(
child: SizedBox(
height: MediaQuery.of(context).size.height,
child: Column(
children: [

In my case, it was happening because I did not use Expanded widget. However, that also did not help to achieve the result. Instead, I used SizedBox with height property like following:

        body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
height: MediaQuery.of(context).size.height,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[


This easily solved my problem.

Explanation

How wrapping a Column > Expanded with another Expanded solves the error.

RenderFlex Unbounded Error

A common nested Column-Expanded hierarchy that gets the "RenderFlex children have non-zero flex but incoming height constraints are unbounded" error:

Screen
→ Column
→ Column
→ Expanded → ERROR

What's happening:

Screen
↓ constraint ↓ (Screen)
Column
Text_A (fixed height: no constraint needed) → OK
Column
↓ constraint ↓ (unbounded)
Text_B (fixed height) → OK
Expanded: calc. height = unbounded - Text_B → ERROR

During layout, a Column performs (in order):

  • fixed-height (i.e. null/zero flex-factor) widget layouts in unbounded space, then...
  • flex-factor sized widgets, calculating remaining space from the parent (i.e. incoming constraints) & the fixed size widgets

Text_A above is fixed-height. It doesn't use incoming constraints for layout.

Expanded though, is a flex-factor widget, sizing itself on remaining space, after fixed-size items are laid out. This requires an incoming constraint (parent size) to do subtraction:

  parent size (constraint) - fixed-items size = remaining space

The 1st Column gets constraints from the device screen (provided via Scaffold, etc.).

But, the 2nd Column (the nested one) is laid out in unbounded space.

Remaining space cannot be calculated:

  unbounded - Text_B = unbounded (error)

Why is a Nested Column Unbounded?

Screen
→ Column
→ Column
→ Expanded

Copied from Column SDK source documentation, Step 1:

/// 1. Layout each child with a null or zero flex factor (e.g., those that are not
///    [Expanded]) with unbounded vertical constraints

The 2nd, nested Column:

  • is a child of Column (the 1st one, obviously), and...
  • has zero or null flex factor

The second point is easy to miss/not see, but Column is not a flex-factor widget.

Checking SDK source...

Column extends Flex class.

Flex, does not have a flex field / flex factor. Only Flexible class and its children are flex factor widgets.

So the 2nd Column is laid out in unbounded constraints because it is not a flex-factor widget. Those unbounded constraints are used to layout Text_B widget (a fixed-size or null flex factor widget), then Expanded tries to calculate remaining space. When trying to calculate remaining space with an unbounded constraint....

  unbounded - Text_B = unbounded (error)

🔥 Expanded explodes 🔥

Flexible

To be hyper-repetitive: Flexible, is the flex-factor widget with a flex field/factor.

Expanded and Spacer are the only child classes of Flexible (that I know of).

So Expanded, Spacer, and Flexible are the only flex-factor widgets and

Flexible != Flex


The Fix - Adding Bounds

Fixing the widget tree:

Screen
→ Column
→ Expanded ← new
→ Column
→ Expanded → OK

Why this works...

Screen
↓ constraint ↓
Column
Text_A ↑ fixed-size ↑
↓ constraint ↓ (calculated: Screen height - Text_A height)
Expanded_A
↓ constraint ↓ (Screen - Text_A)
Column
Text_B ↑ fixed-size ↑
Expanded_B: calc. height = (Screen - Text_A) - Text_B = remaining space → OK

In this case... After fixed-items are laid out (Text_A), remaining space is calculated for Expanded_A:

parent size (screen) - fixed-items (Text_A) = remaining space

Now Expanded_A has a defined amount of space.

Expanded_A provides its size for use by the child Column calculating remaining space for Expanded_B after laying out Text_B.

parent size - fixed-items = remaining space
↓
(Screen - Text_A) - (Text_B) = remaining space for Expanded_B

Now all flex-factor relative sized widgets (i.e. Expanded_A, Expanded_B) have bounded constraints with which to calculate their layout size.

Note that you can use Flexible interchangably here with Expanded. It calculates remaining space the same way as Expanded. It just doesn't force children to fit its size, so they can be smaller if they wish.

Copy/paste Code Action:

NOT OK

/// Unbounded constraint: NOT OK
class RenderFlexUnboundedPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Column(
children: [
Text('Column > Column > Text_A'),
Expanded(
child: Text('Column > Column > Expanded_A')) // explosions
],
)
],
),
);
}
}

OK

/// Constraints provided: OK
class RenderFlexPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Text('Column > Text_A'),
Expanded( // Expanded_A
child: Column(
children: [
Text('Column > Expanded_A > Column > Text_B'),
Expanded( // Expanded_B
child: Text('Column > Expanded_A > Column > Expanded_B'))
],
),
)
],
),
);
}
}

just add shrinkWrap: true if you're using e.g Listview.builder

Setting columns mainAxisSize to min solves in case of SingleChildScrollView since no one acknowledged this so..