Flutter ListView上的查询 [英] Queries on Flutter ListView
本文介绍了Flutter ListView上的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习列表视图,我有以下两个dart文件,一个使用ListView构建器,另一个使用Listview.两者输出相同的结果.我一直在关注listview指南: https://pusher.com/tutorials/flutter-listviews
Im learning about listviews and I have the below two dart files, one using ListView builder and the other Listview. Both output the same result. I have been following the listview guide: https://pusher.com/tutorials/flutter-listviews
以下是我对列表视图的查询:
Below are my queries on listview:
- 我了解现实世界中的数据将来自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是因为它易于理解并且遵循从上到下的顺序,因此易于阅读代码.
- 任何小部件都可以是另一个小部件的子级.取决于您使用它们的方式和用途.
- 许多人说我们应该创建另一个类,然后再次调用它,而不是像上面那样拆分,因为它会影响应用程序的性能.如果仅在一个屏幕上使用很多内容,则可以使用与您自己的方法相同的方法.答案可能是有缺陷的,没什么可给自己的.
这篇关于Flutter ListView上的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文