我有三个复选框(让用户选择不同的难度)。现在,所有复选框均可以单击。
但是出于明显的原因,我只希望用户当时只能选择一个困难-为什么我要为每个新点击都取消选中所有其他框。
在用户选择了难度之后,他将能够做出其他选择。做出选择后,他将自动转到另一个页面。 (换句话说,在用户做出第二选择之前,复选框的选择并不重要。)
我尝试过类似的
void checkBoxes() {
if (_value1 = true) {
_value2 = false;
_value3 = false;
} else if (_value2 = true) {
_value1 = false;
_value3 = false;
} else if (_value3 = true) {
_value1 = false;
_value2 = false;
}
}
但是没有运气。
答案 0 :(得分:1)
您可以通过单击onChanged()方法中的复选框来获取其他变量的更改状态 并将该值分配给复选框小部件,例如:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: MyHomePage(),
));
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool valMonday = false;
bool valTuesday = false;
bool valWednesday = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Group Checkboxes"),
centerTitle: true,
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// [Monday] checkbox
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Monday"),
Checkbox(
value: valMonday,
onChanged: (bool value) {
setState(() {
valMonday = value;
valTuesday = false;
valWednesday = false;
});
},
),
],
),
// [Tuesday] checkbox
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Tuesday"),
Checkbox(
value: valTuesday,
onChanged: (bool value) {
setState(() {
valTuesday = value;
valMonday = false;
valWednesday = false;
});
},
),
],
),
// [Wednesday] checkbox
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Wednesday"),
Checkbox(
value: valWednesday,
onChanged: (bool value) {
setState(() {
valWednesday = value;
valMonday = false;
valTuesday = false;
});
},
),
],
),
],
),
));
}
}