Flutter中如何使用material_segmented_control
在Flutter项目中想使用material_segmented_control实现分段选择器,但遇到几个问题:
- 如何正确安装和导入这个依赖包?
- 基础用法是怎样的?能否给个简单示例代码?
- 如何自定义样式(比如选中/未选中的颜色、文字样式等)?
- 这个控件和CupertinoSlidingSegmentedControl有什么区别?更推荐用哪个?
- 点击切换时如何获取当前选中项的索引或值?
目前试了官方文档但有些配置不太明白,求有经验的开发者分享具体实现方法。
2 回复
在Flutter中使用material_segmented_control,首先在pubspec.yaml中添加依赖:
dependencies:
material_segmented_control: ^最新版本
然后导入包:
import 'package:material_segmented_control/material_segmented_control.dart';
使用示例:
MaterialSegmentedControl(
children: {
0: Text('选项1'),
1: Text('选项2'),
},
selectionIndex: _currentSelection,
onSegmentChosen: (index) {
setState(() {
_currentSelection = index;
});
},
)
需要维护_currentSelection状态变量来跟踪选中项。
更多关于Flutter中如何使用material_segmented_control的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在 Flutter 中使用 material_segmented_control 包可以创建 Material Design 风格的分段控件。以下是基本步骤和示例代码:
步骤:
-
添加依赖:在
pubspec.yaml文件中添加依赖:dependencies: material_segmented_control: ^1.0.0 # 检查最新版本运行
flutter pub get安装包。 -
导入包:
import 'package:material_segmented_control/material_segmented_control.dart'; -
使用组件:在
build方法中添加MaterialSegmentedControl。
示例代码:
int _currentSelection = 0; // 跟踪当前选中项
@override
Widget build(BuildContext context) {
return MaterialSegmentedControl(
children: {
0: Text('选项1'),
1: Text('选项2'),
2: Text('选项3'),
},
selectionIndex: _currentSelection,
onSegmentChosen: (int index) {
setState(() {
_currentSelection = index;
});
},
// 可选:自定义颜色
selectedColor: Colors.blue,
unselectedColor: Colors.grey,
);
}
参数说明:
children:Map 类型,键为索引,值为每个分段显示的 Widget(通常为Text或Icon)。selectionIndex:当前选中项的索引。onSegmentChosen:选择分段时的回调函数,更新状态以反映选择。selectedColor和unselectedColor:自定义选中和未选中状态的颜色。
注意事项:
- 确保在
setState中更新selectionIndex以刷新界面。 - 可调整
borderRadius等属性进一步定制外观。
通过以上步骤,即可在 Flutter 应用中集成分段控件。

