FlutterListViewでのクエリ
Sep 18 2020
リストビューについて学習しています。1つはListViewビルダーを使用し、もう1つはリストビューを使用する以下の2つのダーツファイルがあります。どちらも同じ結果を出力します。私はリストビューガイドに従っています:https://pusher.com/tutorials/flutter-listviews
以下はリストビューでの私の質問です:
- 現実の世界では、データがAPIから取得されることを理解しており、以下のオプションのどれが使用されるのか、またその理由を知りたいのですが。
- コンテナやテキストなどのウィジェットはlistView内の子になることができることを理解するのは正しいですか?
- オプション1では、ListViewの子は関数_buildListItemsFromLocation()です。これは良い習慣ですか、それとも_buildListItemsFromLocation()コードを別のdartファイルに移動する必要がありますか?
オプション1:ListView
class LocationListView extends StatefulWidget {
@override
_LocationListViewState createState() => _LocationListViewState();
}
class _LocationListViewState extends State<LocationListView> {
List<Container> _buildListItemsFromLocation() {
int index = 0;
return locationData.map((location) {
var container = Container(
child: Row(
children: [
Container(
margin: EdgeInsets.all(10.0),
child: Image(
image: AssetImage(location.imagePath),
width: 100.0,
height: 100.0,
fit: BoxFit.cover,
),
),
Container(
child: Text(location.name),
)
],
),
);
return container;
}).toList();
}
@override
Widget build(BuildContext context) {
return ListView(
children: _buildListItemsFromLocation(),
);
}
}
オプション2-ListView.builder
class LocationList extends StatefulWidget {
@override
_LocationListState createState() => _LocationListState();
}
class _LocationListState extends State<LocationList> {
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: locationData.length,
itemBuilder: (context, index) {
return Row(
children: [
Container(
margin: EdgeInsets.all(10.0),
child: Image(
image: AssetImage(locationData[index].imagePath),
width: 100.0,
height: 100.0,
fit: BoxFit.cover,
),
),
Container(
child: Text(locationData[index].name),
)
],
);
}
);
}
}
回答
2 Souvenir Sep 18 2020 at 09:04
- 方法2を使用するのは、理解しやすく、上から下の順序に従うため、コードが読みやすいためです。
- どのウィジェットも別のウィジェットの子になることができます。あなたがそれらをどのようにそして何のために使うかに依存します。
- 多くの人が、アプリのパフォーマンスに影響するため、上記のように分割するのではなく、別のクラスを作成してから再度呼び出す必要があると言います。たくさん使うが1画面だけの場合は、自分と同じ方法で使えます。答えは欠陥があるかもしれません、あなた自身に与えるものは何もありません。
1 Autocrab Sep 18 2020 at 09:01
- 事前にリストのサイズがわからない場合は、ビルダーで作成してください
1.1リストを作成し、要素数が10または12を超えないことがわかっている場合はListView、example1から作成できます。
- 任意のウィジェットをに含めることができます
ListView。便宜上ListTile、先頭、末尾、タイトル、サブタイトルウィジェットを含むと呼ばれるウィジェットがあります - 大丈夫です