我是新手,我在创建包含多个项目的CheckBox时遇到了问题,然后用户也可以从复选框列表中选择多个项目。伙计们,请帮帮我。
答案 0 :(得分:1)
您可以尝试使用此小部件 CheckboxListTile :
import 'package:flutter/material.dart';
class DemoCheck extends StatefulWidget {
@override
DemoCheckState createState() => new DemoCheckState();
}
class DemoCheckState extends State<Demo> {
Map<String, bool> values = {
'foo': true,
'bar': false,
};
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: Text('Demo')),
body: ListView(
children: values.keys.map((String key) {
return new CheckboxListTile(
title: Text(key),
value: values[key],
onChanged: (bool value) {
setState(() {
values[key] = value;
});
},
);
}).toList(),
),
);
}
}
void main() {
runApp( MaterialApp(home: DemoCheck()));
}
答案 1 :(得分:0)
这里有一个完整的例子,说明如何制作它以及如何将价值结合起来
A Map
是 键值 对中的数据集合。 Map 中的数据可以通过其关联的键轻松访问。我们将使用字符串和布尔数据创建一个 Map 数组。字符串是Checkbox的名字,Boolean用来判断哪个checkbox被选中。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.deepPurple[400],
title: Text("Multiple Checkbox Dynamically"),
),
body: SafeArea(
child : Center(
child:DynamicallyCheckbox(),
)
)
),
);
}
}
class DynamicallyCheckbox extends StatefulWidget {
@override
DynamicallyCheckboxState createState() => new DynamicallyCheckboxState();
}
class DynamicallyCheckboxState extends State {
Map<String, bool> List = {
'Egges' : false,
'Chocolates' : false,
'Flour' : false,
'Fllower' : false,
'Fruits' : false,
};
var holder_1 = [];
getItems(){
List.forEach((key, value) {
if(value == true)
{
holder_1.add(key);
}
});
// Printing all selected items on Terminal screen.
print(holder_1);
// Here you will get all your selected Checkbox items.
// Clear array after use.
holder_1.clear();
}
@override
Widget build(BuildContext context) {
return Column (children: <Widget>[
RaisedButton(
child: Text(" Get Checked Checkbox Values "),
onPressed: getItems,
color: Colors.pink,
textColor: Colors.white,
splashColor: Colors.grey,
padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
),
Expanded(
child :
ListView(
children: List.keys.map((String key) {
return new CheckboxListTile(
title: new Text(key),
value: List[key],
activeColor: Colors.deepPurple[400],
checkColor: Colors.white,
onChanged: (bool value) {
setState(() {
List[key] = value;
});
},
);
}).toList(),
),
),]);
}
}
单击“获取选中的复选框值”按钮,您将获得输出
flutter: [Egges, Chocolates, Fllower, Fruits]
来自:https://blog.bajarangisoft.com/blog/how-to-create-multiple-checkbox-dynamically-in-flutter