Just My Life & My Work

[Flutter] Expanded Widget

使用 Expanded Widget 有何效果?Flutter 的 Expanded 更改了行和列子級的約束,指示它們填充可用空間。於是把 Child 包裹在 Expanded 中,看著它成長!😎

以上截圖的程式碼:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Happy Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Center(
        child: Column(
          children: <Widget>[
            Container(
              color: Colors.green,
              height: 100,
              width: 100,
            ),
            Expanded(
              child: Container(
                color: Colors.amber,
                width: 150,
              ),
            ),
            Container(
              color: Colors.blue,
              height: 100,
              width: 200,
            ),
          ],
        ),
      ),
    );
  }
}

可以見到兩張截圖,在螢幕高度不同的狀況下,藍色和綠色的高度固定,而有 Expanded 包裹的黃色,則會跟著螢幕拉高。

有時我們想要依比例來決定空間,我們可以加入 flex 屬性,參考程式碼如下:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Happy Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Center(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 2,
              child: Container(
                color: Colors.green,
                height: 100,
                width: 200,
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                color: Colors.amber,
                width: 200,
              ),
            ),
            Expanded(
              flex: 2,
              child: Container(
                color: Colors.blue,
                height: 100,
                width: 200,
              ),
            )
          ],
        ),
      ),
    );
  }
}

效果如截圖:

可以見到,無論螢幕如何拉高,三個顏色都會依照比例呈現(2:1:2)。

此用法使用 Web 測試會比較方便~🤓

參考:

Expanded class

Expanded (Flutter Widget of the Week)

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: