LoginSignup
1
0

More than 3 years have passed since last update.

【Flutter】GridViewを使って簡単に要素を横に羅列させよう【gridview】

Posted at

この記事を読んで習得できること

FlutterでGridViewを使って、要素をこんな感じに横に並べることが出来るようになる

Simulator Screen Shot - iPhone SE (2nd generation) - 2020-08-15 at 14.14.46.png

結論

こんな感じで書く

main.dart

...

            child: GridView.count(
              padding: EdgeInsets.all(10), // 割と重要!ここでGridViewの位置を調整する
              crossAxisCount: 4, // 一列に要素をいくつまで置けるかを指定
              children: List.generate(
                4, // 要素をいくつ並べるか
                (index) {
                  return Container( 
                    margin: EdgeInsets.all(10), // 要素間の幅を作る
                    child: RaisedButton( // childは今回はRaisedButtonを使用
                      onPressed: () {
                        print("tap");
                      },
                      color: Colors.grey,
                      child: Text(index.toString(), style: TextStyle(fontSize: 16)),
                    ),
                  );
                },
              ),
            ),

ポイント

GridView.countの直下でpaddingを使用する
  →デフォルト値が大きく設定されているので、ほとんどのケースで設定し直さないといけないと思う

crossAxisCountで一列あたりの要素数を決定する
  →固定値でいいと思う

List.generate内で全要素数を指定する
  →ここでは固定値を入れたが、実際は配列の要素数(こんな感じ→array.length)を入れるようにするはず

要素間のスペースはどう開ける?

今回は、margin: EdgeInsets.all(10)で開けたのだが、
公式ではGridView配下でcrossAxisSpacing: 10みたいな方法があったので、
多分こっちの方がいいと思う。

公式を見たい方はこちら

要素数が無限な場合のケースはこちらから。
要素間のスペースの開け方もいろいろあるようで、詳しくはこちらから!

ソース

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0