For循环实现
class HomeContext extends StatelessWidget{
List<Widget> _getData(){
List<Widget> list=new List();
for(var i=1;i<10;i++){//循环创建九条数据
list.add(ListTile(
title: Text("News $i"),
));
}
return list;
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return ListView(
children: this._getData(),//通过私有方法调用
);
}
}
外部引用
dart.dart
List listData=[
{
"title":"News 01",
"author":"author01",
"imgUrl":"http://5b0988e595225.cdn.sohucs.com/images/20171108/e8d0b0ab35b14b33a499d74cbc52b43c.jpeg"
},
{
"title":"News 02",
"author":"author02",
"imgUrl":"http://5b0988e595225.cdn.sohucs.com/images/20171108/ba1b73bec9784b9eae4416226abcddc7.jpeg"
},
{
"title":"News 03",
"author":"author03",
"imgUrl":"http://5b0988e595225.cdn.sohucs.com/images/20171108/fb469ca492a146fd8476fb144cd11f2c.jpeg"
},
{
"title":"News 04",
"author":"author04",
"imgUrl":"http://5b0988e595225.cdn.sohucs.com/images/20171108/d29a69f9c7fc41d1aae4516df8ebfac3.jpeg"
},
{
"title":"News 05",
"author":"author05",
"imgUrl":"http://5b0988e595225.cdn.sohucs.com/images/20171108/d29a69f9c7fc41d1aae4516df8ebfac3.jpeg"
},
{
"title":"News 06",
"author":"author06",
"imgUrl":"http://5b0988e595225.cdn.sohucs.com/images/20171108/d29a69f9c7fc41d1aae4516df8ebfac3.jpeg"
},
];
main.dart先import引入
import 'package:demo/res/data.dart';
class HomeContext extends StatelessWidget{
//自定义方法
List<Widget> _getData(){
List<Widget> list=listData.map((value){
return ListTile(
leading: Image.network(value["imgUrl"]),
title: Text(value['title']),
subtitle: Text(value['author']),
);
}).toList();
return list;
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return ListView(
children: this._getData(),//通过私有方法调用
);
}
}
ListView.builder
class HomeContext extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return ListView.builder(
itemCount: listData.length,//借助前面引入的数据
itemBuilder: (context,index){
return ListTile(
title: Text(listData[index]['title'] ),
subtitle: Text( listData[index]['author'] ),
);
});
}
}
把方法抽离出去
class HomeContext extends StatelessWidget{
Widget _getData(context,index){
return ListTile(
title: Text(listData[index]['title']),
subtitle: Text(listData[index]['author']),
leading: Image.network(listData[index]['imgUrl']),
);
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return ListView.builder(
itemCount: listData.length,
itemBuilder: this._getData);
}
}