您可以在下面复制粘贴运行完整代码
假设_allValues
是List<Map<String, String>>
代码片段
List<Map<String, String>> _allValues = [
{"name": "abc"},
{"name": "def"},
{"name": "123"}
];
FormBuilderFilterChip(
initialValue:
_allValues.map((value) => value['name']).toList(),
attribute: 'filter_chip',
decoration: InputDecoration(
labelText: 'Select many options',
),
options: _allValues
.map(
(val) => FormBuilderFieldOption(
value: val['name'],
child: Text(val['name']),
),
)
.toList(),
工作演示
完整代码
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter FormBuilder Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(color: Colors.purple),
),
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
MyHomePageState createState() {
return MyHomePageState();
}
}
class Data {
String name;
Data(this.name);
}
class MyHomePageState extends State<MyHomePage> {
var data;
bool autoValidate = true;
bool readOnly = false;
bool showSegmentedControl = true;
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
final GlobalKey<FormFieldState> _specifyTextFieldKey =
GlobalKey<FormFieldState>();
ValueChanged _onChanged = (val) => print(val);
var genderOptions = ['Male', 'Female', 'Other'];
List<Map<String, String>> _allValues = [
{"name": "abc"},
{"name": "def"},
{"name": "123"}
];
List<dynamic> _selected;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("FormBuilder Example"),
),
body: Padding(
padding: EdgeInsets.all(10),
child: SingleChildScrollView(
child: Column(children: <Widget>[
FormBuilder(
// context,
key: _fbKey,
autovalidate: true,
initialValue: {
'movie_rating': 5,
},
readOnly: false,
child: Column(
children: <Widget>[
FormBuilderFilterChip(
initialValue: ["Test 1", "Test 3"],
attribute: 'filter_chip',
decoration: InputDecoration(
labelText: 'Select many options',
),
options: [
FormBuilderFieldOption(
value: 'Test', child: Text('Test')),
FormBuilderFieldOption(
value: 'Test 1', child: Text('Test 1')),
FormBuilderFieldOption(
value: 'Test 2', child: Text('Test 2')),
FormBuilderFieldOption(
value: 'Test 3', child: Text('Test 3')),
FormBuilderFieldOption(
value: 'Test 4', child: Text('Test 4')),
],
),
FormBuilderFilterChip(
initialValue:
_allValues.map((value) => value['name']).toList(),
attribute: 'filter_chip',
decoration: InputDecoration(
labelText: 'Select many options',
),
options: _allValues
.map(
(val) => FormBuilderFieldOption(
value: val['name'],
child: Text(val['name']),
),
)
.toList(),
onChanged: (value) {
_selected = value;
print(_selected);
},
)
],
),
),
]),
)));
}
}