Flutter多选插件flutter_multiselect的使用
Flutter多选插件flutter_multiselect的使用
flutter_multiselect
是一个用于在 Flutter 应用程序中实现多选功能的插件。它允许用户从多个选项中选择一个或多个值。
添加依赖
首先,在项目的 pubspec.yaml
文件中添加 flutter_multiselect
依赖:
dependencies:
flutter_multiselect:
然后运行 flutter pub get
来获取依赖包。
导入库
在 Dart 文件中导入 flutter_multiselect
包:
import 'package:flutter_multiselect/flutter_multiselect.dart';
示例:不带定制的多选框
以下是一个简单的示例,展示了如何使用 flutter_multiselect
插件而不进行任何定制:
MultiSelect(
autovalidate: false,
titleText: "Countries",
validator: (value) {
if (value == null) {
return 'Please select one or more option(s)';
}
},
errorText: 'Please select one or more option(s)',
dataSource: [
{
"display": "Australia",
"value": 1,
},
{
"display": "Canada",
"value": 2,
},
{
"display": "India",
"value": 3,
},
{
"display": "United States",
"value": 4,
}
],
textField: 'display',
valueField: 'value',
filterable: true,
required: true,
value: null,
onSaved: (value) {
print('The saved values are $value');
}
)
示例:带定制的多选框
接下来,我们展示如何自定义多选框的外观和行为。例如,我们可以更改按钮栏的颜色、取消按钮文本等:
MultiSelect(
//--------customization selection modal-----------
buttonBarColor: Colors.red,
cancelButtonText: "Exit",
titleText: "Custom Title",
checkBoxColor: Colors.black,
selectedOptionsInfoText: "Selected custom text (tap to remove)",
selectedOptionsBoxColor: Colors.green,
autovalidate: true,
maxLength: 5, // optional
//--------end customization selection modal------------
validator: (dynamic value) {
if (value == null) {
return 'Please select one or more option(s)';
}
return null;
},
errorText: 'Please select one or more option(s)',
dataSource: [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
],
textField: 'name',
valueField: 'code',
filterable: true,
required: true,
onSaved: (value) {
print('The saved values are $value');
},
change: (value) {
print('The selected values are $value');
}
)
完整参数列表
以下是所有可以用来定制多选框模态窗口的参数列表:
类型 | 参数名称 |
---|---|
Color | buttonBarColor |
String | cancelButtonText |
IconData | cancelButtonIcon |
Color | cancelButtonColor |
Color | cancelButtonTextColor |
String | saveButtonText |
IconData | saveButtonIcon |
Color | saveButtonColor |
Color | saveButtonTextColor |
String | clearButtonText |
IconData | clearButtonIcon |
Color | clearButtonColor |
Color | clearButtonTextColor |
String | deleteButtonTooltipText |
IconData | deleteIcon |
Color | deleteIconColor |
Color | selectedOptionsBoxColor |
String | selectedOptionsInfoText |
Color | selectedOptionsInfoTextColor |
IconData | checkedIcon |
IconData | uncheckedIcon |
Color | checkBoxColor |
Color | searchBoxColor |
String | searchBoxHintText |
Color | searchBoxFillColor |
IconData | searchBoxIcon |
String | searchBoxToolTipText |
Size | responsiveDialogSize |
示例代码
以下是从 GitHub 获取的完整示例代码:
import 'package:flutter/material.dart';
import 'package:flutter_multiselect/flutter_multiselect.dart';
import 'cities.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: _rebuilder,
builder: (context, int value, child) {
return MaterialApp(
key: ValueKey(value),
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
themeMode: value.isOdd ? ThemeMode.light : ThemeMode.dark,
theme: ThemeData(primarySwatch: Colors.blue, brightness: Brightness.light),
darkTheme: ThemeData(primarySwatch: Colors.red, brightness: Brightness.dark),
home: MyHomePage(title: 'Flutter Demo - Multiselect'),
);
});
}
}
final _RebuildApp _rebuilder = _RebuildApp();
void rebuildApp() => _rebuilder.execute();
class _RebuildApp extends ValueNotifier<int> {
_RebuildApp() : super(1);
void execute() => value = value + 1;
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, this.title = ''}) : super(key: key);
final String title;
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: [
ElevatedButton(
onPressed: () => rebuildApp(),
child: _rebuilder.value.isOdd ? Text('Switch to Dark theme') : Text('Switch to Light theme'))
],
),
body: Center(
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.always,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: MultiSelect(
autovalidateMode: AutovalidateMode.always,
initialValue: ['IN', 'US'],
titleText: 'Country of Residence',
maxLength: 5, // optional
validator: (dynamic value) {
return value == null ? 'Please select one or more option(s)' : null;
},
errorText: 'Please select one or more option(s)',
dataSource: cities,
textField: 'name',
valueField: 'code',
filterable: true,
required: true,
onSaved: (value) {
print('The saved values are $value');
},
change: (value) {
print('The selected values are $value');
},
selectIcon: Icons.arrow_drop_down_circle,
saveButtonColor: Theme.of(context).primaryColor,
checkBoxColor: Theme.of(context).primaryColorDark,
cancelButtonColor: Theme.of(context).primaryColorLight,
responsiveDialogSize: Size(600, 800),
),
),
SizedBox(width: 10.0),
ElevatedButton(
child: Text('Save'),
style: ElevatedButton.styleFrom(
primary: Theme.of(context).colorScheme.primary,
onPrimary: Theme.of(context).colorScheme.onPrimary,
),
onPressed: () {
_onFormSaved();
}),
SizedBox(
width: 10.0,
),
],
),
),
),
);
}
void _onFormSaved() {
final FormState? form = _formKey.currentState;
form?.save();
}
}
更多关于Flutter多选插件flutter_multiselect的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter多选插件flutter_multiselect的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用Flutter中的flutter_multiselect
插件来实现多选功能的示例代码。这个插件允许用户从一个列表中选择多个项目。
首先,你需要在你的pubspec.yaml
文件中添加flutter_multiselect
依赖:
dependencies:
flutter:
sdk: flutter
flutter_multiselect: ^0.5.0 # 请确保使用最新版本
然后运行flutter pub get
来安装依赖。
接下来,在你的Flutter应用中,你可以使用以下代码来实现多选功能:
import 'package:flutter/material.dart';
import 'package:flutter_multiselect/flutter_multiselect.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter MultiSelect Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<String> options = [
'Option 1',
'Option 2',
'Option 3',
'Option 4',
'Option 5',
];
List<String> selectedOptions = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter MultiSelect Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Selected Options:',
style: TextStyle(fontSize: 18),
),
SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: List.generate(
selectedOptions.length,
(index) => Chip(
label: Text(selectedOptions[index]),
backgroundColor: Colors.blue.shade100,
onDeleted: () {
setState(() {
selectedOptions.removeAt(index);
});
},
),
),
),
SizedBox(height: 20),
MultiSelectChipField<String>(
initialValue: selectedOptions,
label: 'Choose Options',
options: options,
onChanged: (newValue) {
setState(() {
selectedOptions = newValue;
});
},
chipColor: Colors.blue.shade100,
selectedChipColor: Colors.blue,
),
],
),
),
);
}
}
代码解释:
- 依赖导入:在
pubspec.yaml
文件中添加flutter_multiselect
依赖。 - UI布局:
- 使用
Scaffold
、AppBar
和Column
来构建基本的UI结构。 - 使用
Wrap
和Chip
来显示已选择的选项,并且每个Chip
都有一个删除按钮。
- 使用
- MultiSelectChipField:
initialValue
:初始化已选择的选项列表。label
:多选字段的标签。options
:所有可供选择的选项列表。onChanged
:当选项改变时的回调函数,用于更新已选择的选项列表。chipColor
和selectedChipColor
:用于自定义Chip的颜色。
这个示例展示了如何使用flutter_multiselect
插件来创建一个多选界面,并且实时更新和显示用户的选择。你可以根据具体需求进一步自定义和扩展这个示例。