ListView 列表的控件条目 , 一般是遍历集合生成的 ;
如 : 给定如下 List 集合 ;
const NAMES = [ '宋江', '卢俊义', '吴用', '公孙胜', '关胜'];
调用 List 集合的 map 方法 , 可以遍历操作集合中的每一项 , 返回一个新的数组 ;
map 方法的原型如下 ;
Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);
使用 map 方法 , 遍历 NAMES 集合 , 然后传入的匿名方法中 , 返回 Widget 组件 , 那么上述原型中的泛型 T 就是 Widget 类型 ;
下面的方法中 , map 方法传入了一个匿名函数 , 参数是 name , 类型是 String , 返回值是 _generateWidget 函数的返回值 , 其中 _generateWidget 函数返回 Widget 类型 , 最终 map 方法的返回值是 Iterable<Widget> 类型 , 然后调用 toList() 方法 , 将其转为 List<Widget> 类型 ;
NAMES.map((name) => _generateWidget(name)).toList();
完整代码示例 :
import 'package:flutter/material.dart';
const NAMES = [ '宋江', '卢俊义', '吴用', '公孙胜', '关胜',
'林冲', '秦明', '呼延灼', '花荣', '柴进',
'李应', '朱仝', '鲁智深', '武松', '董平',
'张清', '杨志', '徐宁', '索超', '岱宗',
'刘唐', '李逵', '史进', '穆弘' '雷横' ];
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
/// 材料设计主题
return MaterialApp(
home: Scaffold(
appBar: AppBar(
/// 标题组件
title: Text("ListView 示例"),
),
/// 列表组件
body: ListView(
children: _buildList(),
),
),
);
}
/// 创建列表
List<Widget> _buildList(){
/// 遍历 NAMES 数组
/// 调用 map 方法遍历数组元素
return NAMES.map((name) => _generateWidget(name)).toList();
}
Widget _generateWidget(name){
return Container(
height: 80,
margin: EdgeInsets.only(bottom: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.black),
child: Text(
name,
style: TextStyle(
color: Colors.yellowAccent,
fontSize: 20
),
),
);
}
}
执行结果 :
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
const NAMES = [ '宋江', '卢俊义', '吴用', '公孙胜', '关胜',
'林冲', '秦明', '呼延灼', '花荣', '柴进',
'李应', '朱仝', '鲁智深', '武松', '董平',
'张清', '杨志', '徐宁', '索超', '岱宗',
'刘唐', '李逵', '史进', '穆弘' '雷横' ];
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
/// 材料设计主题
return MaterialApp(
home: Scaffold(
appBar: AppBar(
/// 标题组件
title: Text("ListView 示例"),
),
/// 列表组件
body: ListView(
/// 水平滚动设置
scrollDirection: Axis.horizontal,
children: _buildList(),
),
),
);
}
/// 创建列表
List<Widget> _buildList(){
/// 遍历 NAMES 数组
/// 调用 map 方法遍历数组元素
return NAMES.map((name) => _generateWidget(name)).toList();
}
Widget _generateWidget(name){
return Container(
//height: 80,
width: 80,
//margin: EdgeInsets.only(bottom: 5),
margin: EdgeInsets.only(right: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.black),
child: Text(
name,
style: TextStyle(
color: Colors.yellowAccent,
fontSize: 20
),
),
);
}
}
执行结果 :
参考资料 :
重要的专题 :
博客源码下载 :