2017-01-09 85 views
6

假設您有一個可能具有可變大小的父窗口小部件。如何根據父級的大小來佈置小部件?

例如:

var container = new Container(
    height: 200.0, // Imagine this might change 
    width: 200.0, // Imagine this might change 
    // Imagine content in this container will 
    // depend on the parent container 
    child: new Container(), 
); 

也許你想擁有父容器的孩子呈現一些基於大小,它給了什麼不同。

想到響應式設計斷點,如果寬度超過X使用此佈局,如果寬度在X下使用該佈局。

在Flutter中做到這一點的最佳方法是什麼?

+0

撲克wiki引用了一些方法來執行此操作:https://github.com/flutter/flutter/wiki/Creating-Responsive-Apps – Aaron

回答

10

您將需要使用LayoutBuilder小部件,它將在佈局時構建並提供父部件的約束。

LayoutBuilder採用的構建函數的標準爲BuildContext以及BoxConstraints作爲參數,可用於幫助根據大小動態呈現小部件。

讓我們構建一個小部件的簡單示例,如果父寬度大於200dp則呈現「LARGE」,如果父寬度小於或等於該寬度,則呈現「SMALL」。

var container = new Container(
    // Toggling width from 100 to 300 will change what is rendered 
    // in the child container 
    width: 100.0, 
    // width: 300.0 
    child: new LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints) { 
     if(constraints.maxWidth > 200.0) { 
     return new Text('BIG'); 
     } else { 
     return new Text('SMALL'); 
     } 
    } 
), 
); 
相關問題