Just My Life & My Work

[Flutter] Wrap Widget

我們在排列介面時,時常會使用 Row 或 Column,但有時候會超出螢幕,此時該怎麼辦呢?🤔

我們可以改用 Wrap Widget,它擁有跟 Row 或 Column 類似的一些屬性,某些狀況是可以取代之。

以下截圖,是以 Row 和 Column 為例。

可見到右邊和下面介面超出顯示範圍。

上截圖的程式碼:

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: Column(// Row
        children: <Widget>[
          Container(
            color: Colors.green,
            height: 100,
            width: 100,
          ),
          Container(
            color: Colors.red,
            height: 100,
            width: 100,
          ),
          Container(
            color: Colors.blue,
            height: 100,
            width: 100,
          ),
          Container(
            color: Colors.yellow,
            height: 100,
            width: 150,
          ),
          Container(
            color: Colors.black,
            height: 100,
            width: 150,
          ),
        ],
      ),
    );
  }
}

接著我們改用 Wrap,在 Row 的例子中會有什麼效果呢?

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: Wrap(
        // spacing: 8.0, // gap between adjacent chips
        // runSpacing: 50.0, // gap between lines
        // alignment: WrapAlignment.center,
        runAlignment: WrapAlignment.center,
        // direction: Axis.vertical,
        children: <Widget>[
          Container(
            color: Colors.green,
            height: 100,
            width: 100,
          ),
          Container(
            color: Colors.red,
            height: 100,
            width: 100,
          ),
          Container(
            color: Colors.blue,
            height: 100,
            width: 100,
          ),
          Container(
            color: Colors.yellow,
            height: 100,
            width: 150,
          ),
          Container(
            color: Colors.black,
            height: 100,
            width: 150,
          ),
        ],
      ),
    );
  }
}

結果如圖,會將超過的介面移至下一行。

再來我們試著把使用其他屬性,反註解來跑效果如何~

是不是更有彈性呢?介面上下左右的距離可以設定。

參考:

Wrap class

Wrap (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 位部落客按了讚: