在 Flutter 中,PageView Indicator 可以通过 PageView 和 DotIndicator(通常使用 Row 和 Container 自定义)实现。以下是完整示例:
- 使用
PageController 控制 PageView 和指示器同步
- 自定义圆点指示器
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: IndicatorPageView(),
);
}
}
class IndicatorPageView extends StatefulWidget {
@override
_IndicatorPageViewState createState() => _IndicatorPageViewState();
}
class _IndicatorPageViewState extends State<IndicatorPageView> {
final PageController _pageController = PageController();
int _currentPage = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: PageView(
controller: _pageController,
onPageChanged: (int page) {
setState(() {
_currentPage = page;
});
},
children: [
Container(color: Colors.red),
Container(color: Colors.green),
Container(color: Colors.blue),
],
),
),
// 自定义指示器
Container(
padding: EdgeInsets.only(bottom: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(3, (index) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 4),
width: 8,
height: 8,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _currentPage == index
? Colors.blue
: Colors.grey,
),
);
}),
),
),
],
),
);
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
}
关键点说明:
- 使用
PageController 监听页面变化,通过 onPageChanged 更新当前页码 _currentPage
- 指示器通过
Row 和 Container 动态生成,根据 _currentPage 高亮对应圆点
- 可调整圆点大小、颜色、间距等样式
扩展方案:
如需更丰富的效果,可使用第三方库如 flutter_swiper 或 smooth_page_indicator。