4.2 容器類Widget-約束盒子ConstrainedBox和SizedBox容器

ConstrainedBox和SizedBox都是通過RenderConstrainedBox來渲染的。SizedBox只是ConstrainedBox一個(gè)定制,本節(jié)把他們放在一起討論。

ConstrainedBox

ConstrainedBox用于對(duì)齊子widget添加額外的約束
例如,如果你想讓子widget的最小高度是80像素,你可以使用const BoxConstraints(minHeight: 80.0)作為子widget的約束。

class ConstrainedBox extends SingleChildRenderObjectWidget {

  ConstrainedBox({
    Key key,
    @required this.constraints,
    Widget child
  }) : assert(constraints != null),
       assert(constraints.debugAssertIsValid()),
       super(key: key, child: child);
}

constraints用于設(shè)置限制條件,它的定義如下:

const BoxConstraints({
  this.minWidth = 0.0, //最小寬度
  this.maxWidth = double.infinity, //最大寬度
  this.minHeight = 0.0, //最小高度
  this.maxHeight = double.infinity //最大高度
})

示例

我們先定義一個(gè)redBox,它是一個(gè)背景顏色為紅色的盒子,不指定它的寬度和高度:

image.png
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
      
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatelessWidget{

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("測(cè)試Padding"),
      ),
      body: Align(
        alignment: Alignment.topLeft,
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: ConstrainedBoxTest()
      ),
    );
  }
}

class ConstrainedBoxTest extends StatelessWidget{

    @override
    Widget build(BuildContext context){

      return ConstrainedBox(//創(chuàng)建一個(gè)約束盒子

        constraints:BoxConstraints(//約束規(guī)則

          minWidth: double.infinity,//最小寬度無限大
          minHeight: 50,//最小高度為50像素
        ),
        child: Container(
          height: 5,//指定子盒子高度為5

          //添加紅色子盒子
          child: DecoratedBox(
            decoration: BoxDecoration(color: Colors.red),
          ),
        ),
      );
    }
}

SizedBox

SizedBox用于給子widget指定固定的寬高,如:

SizedBox(
  width: 80.0,
  height: 80.0,
  child: redBox
)

運(yùn)行效果:

實(shí)際上SizedBox和只是ConstrainedBox一個(gè)定制,上面代碼等價(jià)于:

ConstrainedBox(
  constraints: BoxConstraints.tightFor(width: 80.0,height: 80.0),
  child: redBox, 
)

而BoxConstraints.tightFor(width: 80.0,height: 80.0)等價(jià)于:

BoxConstraints(minHeight: 80.0,maxHeight: 80.0,minWidth: 80.0,maxWidth: 80.0)

而實(shí)際上ConstrainedBox和SizedBox都是通過RenderConstrainedBox來渲染的,我們可以看到ConstrainedBox和SizedBox的createRenderObject()方法都返回的是一個(gè)RenderConstrainedBox對(duì)象:

@override
RenderConstrainedBox createRenderObject(BuildContext context) {
  return new RenderConstrainedBox(
    additionalConstraints: ...,
  );
}

多重限制

如果某一個(gè)widget有多個(gè)父ConstrainedBox限制,那么最終會(huì)是哪個(gè)生效?我們看一個(gè)例子:

ConstrainedBox(
    constraints: BoxConstraints(minWidth: 60.0, minHeight: 60.0), //父
    child: ConstrainedBox(
      constraints: BoxConstraints(minWidth: 90.0, minHeight: 20.0),//子
      child: redBox,
    )
)

上面我們有父子兩個(gè)ConstrainedBox,他們的限制條件不同,運(yùn)行后效果如下:

最終顯示效果是寬90,高60,也就是說是子ConstrainedBox的minWidth生效,而minHeight是父ConstrainedBox生效。單憑這個(gè)例子,我們還總結(jié)不出什么規(guī)律,我們將上例中父子限制條件換一下:

ConstrainedBox(
    constraints: BoxConstraints(minWidth: 90.0, minHeight: 20.0),
    child: ConstrainedBox(
      constraints: BoxConstraints(minWidth: 60.0, minHeight: 60.0),
      child: redBox,
    )
)

最終的顯示效果仍然是90,高60,效果相同,但意義不同,因?yàn)榇藭r(shí)minWidth生效的是父ConstrainedBox,而minHeight是子ConstrainedBox生效。

通過上面示例,我們發(fā)現(xiàn)

有多重限制時(shí),對(duì)于minWidth和minHeight來說,是取父子中相應(yīng)數(shù)值較大的。實(shí)際上,只有這樣才能保證父限制與子限制不沖突。

![](https://upload-images.jianshu.io/upload_images/2160098-daa70e0e288b9703.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
//測(cè)試多重盒子約束
class MutlConstrainedBoxTest extends StatelessWidget{

   @override
    Widget build(BuildContext context){
      return Column(

        children: <Widget>[

          Container(  //創(chuàng)建一個(gè)寬高60的參考盒子
            width: 60,
            height: 60,

            color: Colors.green,
          ),

          ConstrainedBox(//父盒子
            constraints: BoxConstraints(
              maxHeight: 60,
              maxWidth: 90
              
            ),

            child: ConstrainedBox(

              constraints: BoxConstraints(
                maxHeight: 90,
                maxWidth: 60
              ),
              child: Container(
                color: Colors.red,
              )
            ),
          )
        ],
      );
    }
}

有多重限制時(shí),對(duì)于maxHeight和maxWidth來說,是取父子中相應(yīng)數(shù)值較小的。

UnconstrainedBox

UnconstrainedBox不會(huì)對(duì)子Widget產(chǎn)生任何限制,它允許其子Widget按照其本身大小繪制。一般情況下,我們會(huì)很少直接使用此widget,但在"去除"多重限制的時(shí)候也許會(huì)有幫助,我們看一下面的代碼:

ConstrainedBox(
    constraints: BoxConstraints(minWidth: 60.0, minHeight: 100.0),  //父
    child: UnconstrainedBox( //“去除”父級(jí)限制
      child: ConstrainedBox(
        constraints: BoxConstraints(minWidth: 90.0, minHeight: 20.0),//子
        child: redBox,
      ),
    )
)

上面代碼中,如果沒有中間的UnconstrainedBox,那么根據(jù)上面所述的多重限制規(guī)則,那么最終將顯示一個(gè)90×100的紅色框。但是由于 UnconstrainedBox “去除”了父ConstrainedBox的限制,則最終會(huì)按照子ConstrainedBox的限制來繪制redBox,即90×20:

但是,UnconstrainedBox對(duì)父限制的“去除”并非是真正的去除,上面例子中雖然紅色區(qū)域大小是90×20,但上方仍然有80的空白空間。也就是說父限制的minHeight(100.0)仍然是生效的,只不過它不影響最終子元素的大小,但仍然還是占有相應(yīng)的空間,可以認(rèn)為此時(shí)的父ConstrainedBox是作用于子ConstrainedBox上,而redBox只受子ConstrainedBox限制,這一點(diǎn)請(qǐng)讀者務(wù)必注意。

那么有什么方法可以徹底去除父BoxConstraints的限制嗎?答案是否定的!所以在此提示讀者,在定義一個(gè)通用的widget時(shí),如果對(duì)子widget指定限制時(shí)一定要注意,因?yàn)橐坏┲付ㄏ拗茥l件,子widget如果要進(jìn)行相關(guān)自定義大小時(shí)將可能非常困難,因?yàn)樽觲idget在不更改父widget的代碼的情況下無法徹底去除其限制條件。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 原文在此,此處只為學(xué)習(xí) Widget與ElementWidget主要接口Stateless WidgetState...
    lltree閱讀 4,626評(píng)論 0 1
  • 鹿白的意識(shí)在慢慢蘇醒,莫名的警惕感讓他不敢貿(mào)然睜眼,他就這樣躺著,像一只蟲子一樣靜靜地感知周圍的環(huán)境。有風(fēng)輕輕地吹...
    廣厘閱讀 380評(píng)論 1 2
  • 寒風(fēng)蕭蕭,愁濃夢(mèng)少,淚灑心湖。憶月圓時(shí)候,脈脈含情;道字嬌訛,細(xì)卷青絲。想來心連,一表真言。無語凝噎,遠(yuǎn)在咫尺,縱...
    浪丶中大閱讀 204評(píng)論 0 0
  • 早先在做漢字簡(jiǎn)化的時(shí)候還有進(jìn)一步的方案就是拼音化,拼音化是為方便接收英文外來詞作基礎(chǔ)。 英文的 I love yo...
    謝子德閱讀 831評(píng)論 0 1
  • 下午給孩子家長(zhǎng)會(huì),感受很多。一個(gè)好的習(xí)慣會(huì)讓孩子在學(xué)習(xí)和生活中受益終生。按時(shí)起床,不遲到早退,上課認(rèn)真聽講,認(rèn)真完...
    Acumey閱讀 114評(píng)論 0 0

友情鏈接更多精彩內(nèi)容