ListView class, flutter里面的滚动列表,用它可以代替我们常用的scrollView,实现tableView效果也是首选。后续文章会结合GridView class来实现一个首页顶部的广告栏横向轮播,以及商品瀑布流的展示。
文档中,给出了下面三种调用方式
- 动态列表,通过ListView.builder。默认情况下,ListView将自动填充列表的可滚动末端,以避免MediaQuery填充指示的部分障碍,使用零填充属性覆盖可以避免此行为。
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
backgroundColor: Colors.white,
body: Center(
child:Container(
height: 200.0,
child: TopAd(
items:new List.generate(10, (i)=>"Item $i")
),
),
)
);
}
}
class TopAd extends StatelessWidget{
@override
final List items;
TopAd({key,@required this.items}):super(key:key); //重写构造方法
Widget build(BuildContext context) {
// TODO: implement build
return ListView.builder(
padding: EdgeInsets.all(8.0),
itemBuilder: (context,index){
return new ListTile(
title: new Text('${items[index]}'),
);
},
itemCount: items.length,
);
}
}
- 静态列表,通过 ListView 或者 CustomScrollView创建对象,直接往children属性里面添加视图。
ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(20.0),
children: [
const Text('I\'m dedicating every day to you'),
const Text('Domestic life was never quite my style'),
const Text('When you smile, you knock me out, I fall apart'),
const Text('And I thought I was so smart'),
],
)
CustomScrollView(
shrinkWrap: true,
slivers: [
SliverPadding(
padding: const EdgeInsets.all(20.0),
sliver: SliverList(
delegate: SliverChildListDelegate(
[
const Text('I\'m dedicating every day to you'),
const Text('Domestic life was never quite my style'),
const Text('When you smile, you knock me out, I fall apart'),
const Text('And I thought I was so smart'),
],
),
),
),
],
)
我们可以发觉ListView是默认纵向滑动的,那我们如何设置它为横向滑动呢?设置scrollDirection !
- Axis.horizontal 横向滚动
- Axis.vertiacal 纵向滚动
import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:math';
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
backgroundColor: Colors.white,
body:
Center(
child:Container(
height: 200.0,
child: TopAd(),
),
)
);
}
}
class TopAd extends StatelessWidget{
@override
var random = Random();
Widget build(BuildContext context) {
// TODO: implement build
return ListView(
scrollDirection: Axis.horizontal,
children: [
Container(
width: window.physicalSize.width,
color: Color.fromARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), 1),
),
Container(
width: 150.0,
color: Color.fromARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), 1),
),
],
);
}
}