Flutter中如何创建横向滚动卡片?含带指示器单屏单张实现
Flutter 横向滚动卡片实现方案
一、基础横向滚动卡片
如果只需要简单的横向滚动卡片列表,用ListView配合scrollDirection: Axis.horizontal就能快速实现:
ListView.builder( scrollDirection: Axis.horizontal, padding: EdgeInsets.symmetric(horizontal: 16), itemCount: 5, itemBuilder: (context, index) { return Container( width: 280, margin: EdgeInsets.only(right: 12), child: Card( elevation: 4, child: Padding( padding: EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('卡片 $index', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), SizedBox(height: 8), Text('这是横向滚动卡片的示例内容'), ], ), ), ), ); }, )
二、单屏仅显示一张卡片+指示器的效果
要实现单屏一张、带页面指示器的效果,推荐用PageView组件,它天生支持单页切换,再配合页面控制器和自定义指示器即可:
核心实现代码
class HorizontalCardWithIndicator extends StatefulWidget { @override _HorizontalCardWithIndicatorState createState() => _HorizontalCardWithIndicatorState(); } class _HorizontalCardWithIndicatorState extends State<HorizontalCardWithIndicator> { final PageController _pageController = PageController(); int _currentPage = 0; final List<String> _cardContents = [ '卡片内容1', '卡片内容2', '卡片内容3', '卡片内容4', ]; @override void initState() { super.initState(); _pageController.addListener(() { setState(() { _currentPage = _pageController.page?.round() ?? 0; }); }); } @override void dispose() { _pageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( children: [ // 单屏滚动卡片区域 SizedBox( height: 200, child: PageView.builder( controller: _pageController, itemCount: _cardContents.length, itemBuilder: (context, index) { return Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: Card( elevation: 6, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), child: Center( child: Text( _cardContents[index], style: TextStyle(fontSize: 20), ), ), ), ); }, ), ), SizedBox(height: 16), // 页面指示器 Row( mainAxisAlignment: MainAxisAlignment.center, children: List.generate(_cardContents.length, (index) { return Container( width: 8, height: 8, margin: EdgeInsets.symmetric(horizontal: 4), decoration: BoxDecoration( shape: BoxShape.circle, color: _currentPage == index ? Colors.blue : Colors.grey.shade300, ), ); }), ), ], ); } }
说明
PageController用于控制页面切换,同时监听页面变化更新当前索引- 自定义指示器用
Row生成圆形小点,通过_currentPage控制激活状态的颜色 - 如果需要更丰富的指示器样式,可使用第三方包(如
flutter_page_indicator)替换底部的Row组件
内容的提问来源于stack exchange,提问作者Phanindra
相关产品推荐
相关产品推荐

