Flutter 中的ListView相当于Android中的Scrollview也相当于Android中的ListView。
children: []
scrollDirection: Axis.horizontal, //滑动方向
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "ListView",
home: Scaffold(
appBar: AppBar(
title: new Text("ListViewDemo"),
),
body: MyListViewHorizontal()),
);
}
}
class MyListViewVertical extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new ListView(
children: getWidgets(),
// [
// new ListTile(
// leading: new Icon(Icons.access_alarm),
// title: new Text("access_alarm"),
// ),
// new ListTile(
// leading: new Icon(Icons.access_time),
// title: new Text("access_time"),
// ),
// new ListTile(
// leading: new Icon(Icons.accessibility_new),
// title: new Text("accessibility_new"),
// ),
// ],
);
}
List getWidgets() {
List widgets = new List();
for (int i = 0; i < 10; i++) {
widgets.add(new ListTile(
leading: new Icon(Icons.access_alarm),
title: new Text("access_alarm"),
));
widgets.add(new ListTile(
leading: new Icon(Icons.access_time),
title: new Text("access_time"),
));
widgets.add(new ListTile(
leading: new Icon(Icons.accessibility_new),
title: new Text("accessibility_new"),
));
}
return widgets;
}
}
class MyListViewHorizontal extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Center(
child: new Container(
height: 200,
child: new ListView(
scrollDirection: Axis.horizontal,
children: getWidgets(),
),
));
}
List getWidgets() {
List widgets = new List();
for (int i = 0; i < 10; i++) {
widgets.add(new Container(
color: Colors.blue,
width: 200,
));
widgets.add(new Container(
color: Colors.yellow,
width: 200,
));
widgets.add(new Container(
color: Colors.red,
width: 200,
));
}
return widgets;
}
}
学习点:
1、动态ListView 使用ListView.Builder 创建,常用属性:itemCount: items.length, itemBuilder: (context,index){}
2、组件传递参数 其中组件构造器中的Key key是默认的参数必须写的,其他参数当为必须传递的参数时需要添加@required
import 'package:flutter/material.dart';
void main() => runApp(MyApp(
items: new List.generate(100, (i) => "Item $i"),
));
class MyApp extends StatelessWidget {
final List items;
MyApp({Key key, @required this.items}) : super(key: key);
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "ListView",
home: new Scaffold(
appBar: AppBar(
title: new Text("ListView Dynamic"),
),
body: new ListView.builder(
itemCount: items.length,
itemBuilder: (context,index){
return new ListTile(
title: new Text("${items[index]}"),
);
},
),
),
);
}
}