Flutter开发(十三)—— PageView不一样的ViewPage(Android原生)
组织数据,之前博客中有使用过。
class Animal {
final String name;
final String image;
final String description;
Animal({this.name, this.image, this.description});
static List<Animal> allAnimal() {
var animal = List<Animal>();
animal.add(Animal(
name: "老虎",
description: "老虎屁股摸不得!",
image: "https://dwz.cn/ghiCDaUp",
));
animal.add(Animal(
name: "小狗",
description: "小狗啃骨头",
image: "https://dwz.cn/Isoze9KN",
));
animal.add(Animal(
name: "小猫",
description: "小猫吃鱼",
image: "https://dwz.cn/x4dNzR6r",
));
animal.add(Animal(
name: "老鼠",
description: "老鼠会打洞",
image: "https://dwz.cn/1WeGTFA5",
));
animal.add(Animal(
name: "小鸡",
description: "小鸡本米尺",
image: "https://dwz.cn/SXhBUBCP",
));
return animal;
}
}
PageView的使用和属性介绍(看注释)
import 'package:flutter/material.dart';
import 'Animal.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
List<Animal> animals = Animal.allAnimal(); //组织Animal 的List,提供展示数据
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false, //去掉右上角debug标签,并且没有写AppBar
title: "Hello",
home: Scaffold(
// body: PageViewTest(),
body: PageView.builder(
pageSnapping: false, //默认true,即拖动不到一半弹回原页面;flase即,拖到哪里停在哪
scrollDirection:
Axis.vertical, //垂直切换还是水平切换(默认水平,Android原生ViewPage要费很大劲才能实现)
reverse: false, //倒置,设置true页面顺序从后往前,默认false
onPageChanged: (currentIndex) =>
debugPrint('当前页面:$currentIndex'), //onPageChanged 监听页面改变,输出当前页面序号
controller: PageController(
initialPage: 1, //默认显示第几个页面(默认0)
keepPage: false, //设置为true initialPage才生效(默认true)
viewportFraction: 1.0 //默认1,每个页面占可视窗的比例
),
itemCount: Animal.allAnimal().length, //数量
itemBuilder: _pageItemAnimal, //展示具体的Widget
),
),
);
}
//定义一个 Stack 返回展示
Widget _pageItemAnimal(BuildContext context, int index) {
return Stack(
children: <Widget>[
SizedBox.expand(
child: Image.network(
animals[index].image,
fit: BoxFit.cover,
),
),
Positioned(
bottom: 20.0,
left: 20.0,
child: Text(
animals[index].description,
style: TextStyle(color: Colors.deepOrangeAccent, fontSize: 30.0),
),
),
],
);
}
}
效果展示:(垂直、水平滑动只是一个属性设置: scrollDirection: Axis.vertical,)
超级丝滑!