flutter for循环:
dart
Wrap(
children: <Widget>[
for (int i = 0; i < (xx.yy.data?.items?.length ?? 0); i++)
TextButton(onPressed: (){}, child: Text("${xx.yy.data?.items?[i].name.toString()} (${xx.yy.data?.items?[i].connId.toString()}) "))
],
);
另一种方法:
dart
import 'package:flutter/material.dart';
import './fonts.dart';
import 'package:flutter_basic/res/listData.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('hello flutter'),
),
body: const Myapp(),
),
));
}
class Myapp extends StatelessWidget {
const Myapp({Key? key}) : super(key: key);
/// 定义组件
/// 第一种方法:for循环
// List<Widget> _initListData() {
// List<Widget> tempList = [];
// for (var i = 0; i < listData.length; i++) {
// tempList.add(ListTile(
// leading: Image.network("${listData[i]["imageUrl"]}"),
// title: Text("${listData[i]["title"]}"),
// subtitle: Text("${listData[i]["author"]}"),
// ));
// }
// return tempList;
// }
///第二种方法:map
List<Widget> _initListData() {
var tempList = listData.map((e) {
return ListTile(
leading: Image.network("${e["imageUrl"]}"),
title: Text("${e["title"]}"),
subtitle: Text("${e["author"]}"),
);
});
return tempList.toList();
}
@override
Widget build(BuildContext context) {
print(listData);
return ListView(
children: _initListData(),///使用
);
}
}
使用ListView提供的builder构造函数来生成一个动态列表,在builder里需要传人两个必传参数itemCount、itemBuilder
dart
class Myapp extends StatelessWidget {
const Myapp({Key? key}) : super(key: key);
///使用ListView提供的builder构造函数来生成一个动态列表
/// 在builder里需要传人两个必传参数itemCount、itemBuilder
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: listData.length,
itemBuilder: (context, index) {
return ListTile(
leading: Image.network("${listData[index]["imageUrl"]}"),
title: Text("${listData[index]["title"]}"),
subtitle: Text("${listData[index]["author"]}"),
);
});
}
}