LoginSignup
2
3

More than 3 years have passed since last update.

[Flutter]ListViewが難しかった

Last updated at Posted at 2020-03-19

きっかけ

長期休みに入り興味があったFlutterを始めた。
いろいろやってみて、まずListViewにつまづいた。つまづいたポイントとして、

  • クラスの使い方
  • 要素のUIの構成
  • どのように要素にデータを渡すか

がある。

開発はXamarinを軽く触ったことがある程度で、初心者。
書籍は基礎から学ぶFlutterを購入し、公式サイトも見ながらスタートしたFlutter超初心者。また、Flutterを開発するにあたって日本語の記事が異常に少ないので書こうと思った。これからも何かつまづくことがあればちょくちょく書く予定。

ListView

ListViewとは要素をスクロールできる画面に表示していくウィジェット。
FlutterにはYoutubeに公式チャンネルがあり、多くのウィジェットの紹介動画があり、短く、見やすい動画となっているのでおすすめ。もちろんListViewの動画もある。
ListView (Flutter Widget of the Week)

ListView.separated

ちょっと調べてみて、ListView.separatedコンストラクタが使いやすそうだったので使ってみた。
他にもListViewListView.builderListView.customがあるがまだよくわからない(そのうち追記するかも)。
ListView.separatedコンストラクタの使用例は、最後に書いたので参考にして欲しい。

公式サイトによると、このコンストラクタは以下のようになっているらしい。

https://api.flutter.dev/flutter/widgets/ListView/ListView.separated.html

ListView.separated({
Key key,
Axis scrollDirection: Axis.vertical,
bool reverse: false,
ScrollController controller,
bool primary,
ScrollPhysics physics,
bool shrinkWrap: false,
EdgeInsetsGeometry padding,
@required IndexedWidgetBuilder itemBuilder,
@required IndexedWidgetBuilder separatorBuilder,
@required int itemCount,
bool addAutomaticKeepAlives: true,
bool addRepaintBoundaries: true,
bool addSemanticIndexes: true,
double cacheExtent
})

@requiredがついているものは必須の引数で、これらを解説する。

itemBuilder

この引数には、ListViewのアイテムを作るウィジェットを入れる。ここのウィジェットで作ったものがListViewの1アイテムとしてitemCountの数分作られる。
また、関数は

sample.dart
Widget functionName(BuildContext context, int index){}

のように書く。

separatorBuilder

itemBuilderと同様の形式の関数を書く。公式サイトより引用し、

sample.dart
(BuildContext context, int index) => Divider()

と書いたが、よくわかっていないため後に追記する。
(知っている方いたら教えてください!)

itemCount

要素数。int型の整数値のみを入れる。List<T> listを使う場合、list.lengthを使うといいっぽい。

使用例

書いてみたプログラムと実行結果。

プログラム

sample.dart
import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MainPage(),
    );
  }
}

class Person {
  int age;
  final String name;
  Person({this.age, this.name});
}

class MainPage extends StatelessWidget {
  List<Person> _data = [
    Person(age: 20, name: "Satou"),
    Person(age: 18, name: "Suzuki"),
    Person(age: 30, name: "Tanaka")
  ];

  Widget MyListView() {
    return ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          return Container(
            padding: EdgeInsets.all(10),
            child: Row(
              children: <Widget>[
                Container(
                  alignment: Alignment.topLeft,
                  child: Text(
                    _data[index].name,
                    style: TextStyle(fontSize: 25)
                  ),
                ),
                Spacer(),
                Container(
                  alignment: Alignment.bottomRight,
                  child: Text(
                    _data[index].age.toString(),
                    style: TextStyle(fontSize: 20)
                  ),
                )
              ],
            )
          );
        },
        separatorBuilder: (BuildContext context, int index) => Divider(),
        itemCount: _data.length);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: Text("List Page")),
            body: Container(color: Colors.white, child: MyListView())));
  }
}

実行結果

スクリーンショット 2020-03-19 22.17.15.png

2
3
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
2
3