# Flutter的盒子约束

2019/04/10 10:10

##### 由Expanded widget引发的思考

<img style="width:40%;height:40%" src="https://i.loli.net/2020/03/11/v8XIFqzTVhfbYZP.png" alt="flutter效果图" align=center />

<img style="width:60%;height:60%" src="https://i.loli.net/2020/03/11/FHU3LQA5hBqyzws.png" alt="flutter效果图" align=center />

  @override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListView.builder(
itemCount: 30,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text("标题$index"), ); }, ), ], ); }  当然这样仅仅这样写，在手机屏幕上会看到一片空白，如果是debug模式，则会在控制台中看到如下报错 ════════ Exception caught by rendering library ═════════════════════════════════ RenderBox was not laid out: RenderRepaintBoundary#e7255 relayoutBoundary=up2 NEEDS-PAINT 'package:flutter/src/rendering/box.dart': Failed assertion: line 1687 pos 12: 'hasSize' The relevant error-causing widget was Column 从报错信息可以得知是Column widget出错了，RenderBox未正确布局等等。 正确的写法 @override Widget build(BuildContext context) { return Column( children: <Widget>[ Expanded( child: ListView.builder( itemCount: 30, itemBuilder: (BuildContext context, int index) { return ListTile( title: Text("标题$index"),
);
},
),
),
],
);
}


Expanded widget作用是给子 widget 分配剩余的空间，也就是只要给ListView指定高度即可。当然也就可以在ListView外层嵌套一个限定高度的Container widget。

##### Flutter盒子

In Flutter, widgets are rendered by their underlying RenderBox objects. Render boxes are given constraints by their parent, and size themselves within those constraints. Constraints consist of minimum and maximum widths and heights; sizes consist of a specific width and height. Generally, there are three kinds of boxes, in terms of how they handle their constraints:

• Those that try to be as big as possible. For example, the boxes used by Center and ListView.
• Those that try to be the same size as their children. For example, the boxes used by Transform and Opacity
• Those that try to be a particular size. For example, the boxes used by Image and Text.

• 无限制边界（在某一个方向，比如纵向滚动那么宽度就是受限制的而高度无边界，并不是宽高都任意大），例如Center和ListView widget
• 由子widget的宽高决定了自己的边界，如 Transform 和 Opacity
• 有确定的宽高大小，如 Image和Text widget

A box that tries to be as big as possible won’t function usefully when given an unbounded constraint and, in debug mode, such a combination throws an exception that points to this file.

The most common cases where a render box finds itself with unbounded constraints are within flex boxes (Row and Column), and within scrollable regions (ListView and other ScrollView subclasses).

0
0 收藏

0 评论
0 收藏
0