本节代码利用Flutter的ListView组件实现垂直/水平方向滚动的列表,效果图如下:
垂直方向的滚动:
代码语言:javascript复制import 'package:flutter/material.dart';
void main() => runApp(MyApp());
const CITY_NAMES = ['北京','上海','广州','深圳','杭州','武汉','四川','重庆',
'南京','济南','青岛','大连','苏州','南昌'
];
class MyApp extends StatelessWidget {
final title = 'Basic ListView';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: ListView(
scrollDirection: Axis.vertical,
children: _buildList(),
)),
);
}
List<Widget> _buildList() {
return CITY_NAMES.map((city) => _item(city)).toList();
}
Widget _item(String name) {
return Container(
height: 80,
margin: EdgeInsets.only(bottom: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.green),
child: Text(
name,
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
);
}
}
水平方向滚动的列表只需要给ListView添加scrollDirection属性,并设置为Axis.horizontal:
代码语言:javascript复制import 'package:flutter/material.dart';
void main() => runApp(MyApp());
const CITY_NAMES = ['北京','上海','广州','深圳','杭州','武汉','四川','重庆',
'南京','济南','青岛','大连','苏州','南昌'
];
class MyApp extends StatelessWidget {
final title = 'Basic ListView';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: ListView(
scrollDirection: Axis.horizontal,
children: _buildList(),
)),
);
}
List<Widget> _buildList() {
return CITY_NAMES.map((city) => _item(city)).toList();
}
Widget _item(String name) {
return Container(
width: 100,
margin: EdgeInsets.only(right: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.green),
child: Text(
name,
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
);
}
}