Flutter 中的 PageView 控件:全面指南
在Flutter中,PageView
是一个强大的控件,它允许用户滚动查看多个页面。以下是一个简单的PageView
使用指南和示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PageViewDemo(),
);
}
}
class PageViewDemo extends StatefulWidget {
@override
_PageViewDemoState createState() => _PageViewDemoState();
}
class _PageViewDemoState extends State<PageViewDemo> {
int currentPage = 0;
@override
Widget build(BuildContext context) {
final pages = [
Color(0xFFffd900),
Color(0xFFff7f00),
Color(0xFFff3339),
Color(0xFFff1744),
];
return Scaffold(
body: PageView(
onPageChanged: (index) {
setState(() {
currentPage = index;
});
},
children: pages.map((color) => Container(
color: color,
)).toList(),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: currentPage,
onTap: (index) {
setState(() {
currentPage = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.business), title: Text('Business')),
BottomNavigationBarItem(icon: Icon(Icons.school), title: Text('School')),
BottomNavigationBarItem(icon: Icon(Icons.person_pin), title: Text('Person')),
],
),
);
}
}
这个例子中,我们创建了一个PageView
,它包含了四个页面,每个页面都是一个颜色。同时,我们添加了一个BottomNavigationBar
来控制当前显示的页面。这个例子展示了如何使用PageView
和BottomNavigationBar
来创建一个简单的页面滚动和切换的用户界面。
评论已关闭