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)

Comments on: "[Flutter] Wrap Widget" (1)

  1. HappyMan 的大頭貼

    今日有用在加密專案上~🙃

回覆給HappyMan 取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲