无法在复选框之间切换。

huangapple go评论65阅读模式
英文:

Cannot toggle between the checkboxes

问题

我在切换复选框之间遇到了困难。我希望当一个复选框被选中时,如果用户选中另一个复选框,前一个复选框应取消选中,反之亦然。

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    bool mIsChecked = false;
    bool fIsChecked = false;
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'BMI Calculator',
          style: TextStyle(fontSize: 15),
        ),
        centerTitle: true,
        elevation: 0,
      ),
      body: Column(
        children: [
          TextContainer(
            size: size,
            text: 'I am a ',
          ),
          const SizedBox(height: 50),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Column(
                children: [
                  const CircleImage(gender: 'male'),
                  StatefulBuilder(
                    builder: (BuildContext context, StateSetter setState) {
                      return Transform.scale(
                        scale: 1.5,
                        child: Checkbox(
                          value: mIsChecked,
                          onChanged: (bool? value) {
                            setState(() {
                              if (fIsChecked == true) {
                                fIsChecked = false;
                              }
                              mIsChecked = value!;
                            });
                            // print('isChecked: $isChecked');
                          },
                          // activeColor: Colors.green,
                          fillColor: MaterialStateProperty.resolveWith<Color>(
                              (Set<MaterialState> states) {
                            if (states.contains(MaterialState.disabled)) {
                              return const Color(0xFF00BB6E).withOpacity(.32);
                            }
                            return const Color(0xFF00BB6E);
                          }),
                          materialTapTargetSize: MaterialTapTargetSize.padded,
                        ),
                      );
                    },
                  ),
                ],
              ),
              Column(
                children: [
                  const CircleImage(gender: 'female'),
                  StatefulBuilder(
                    builder: (BuildContext context, StateSetter setState) {
                      return Transform.scale(
                        scale: 1.5,
                        child: Checkbox(
                          value: fIsChecked,
                          onChanged: (bool? value) {
                            setState(() {
                              if (mIsChecked == true) {
                                mIsChecked = false;
                              }
                              fIsChecked = value!;
                            });
                            // print('isChecked: $isChecked');
                          },
                          // activeColor: Colors.green,
                          fillColor: MaterialStateProperty.resolveWith<Color>(
                              (Set<MaterialState> states) {
                            if (states.contains(MaterialState.disabled)) {
                              return const Color(0xFF00BB6E).withOpacity(.32);
                            }
                            return const Color(0xFF00BB6E);
                          }),
                          materialTapTargetSize: MaterialTapTargetSize.padded,
                        ),
                      );
                    },
                  ),
                ],
              ),
            ],
          )
        ],
      ),
    );
  }
}

我尝试了不同的检查方式,但我认为我在条件部分做错了,这就是为什么它没有切换的原因。

英文:

I'm having difficulty toggling between the check boxes. What i want is the when one checkbox is checked and if the user checks the other checkbox the previous one should uncheck and viceversa.

class _HomeScreenState extends State&lt;HomeScreen&gt; {
@override
Widget build(BuildContext context) {
bool mIsChecked = false;
bool fIsChecked = false;
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: const Text(
&#39;BMI Calculator&#39;,
style: TextStyle(fontSize: 15),
),
centerTitle: true,
elevation: 0,
),
body: Column(
children: [
TextContainer(
size: size,
text: &#39;I am a &#39;,
),
const SizedBox(height: 50),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: [
const CircleImage(gender: &#39;male&#39;),
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Transform.scale(
scale: 1.5,
child: Checkbox(
value: mIsChecked,
onChanged: (bool? value) {
setState(() {
if (fIsChecked == true) {
fIsChecked = false;
}
mIsChecked = value!;
});
// print(&#39;isChecked: $isChecked&#39;);
},
// activeColor: Colors.green,
fillColor: MaterialStateProperty.resolveWith&lt;Color&gt;(
(Set&lt;MaterialState&gt; states) {
if (states.contains(MaterialState.disabled)) {
return const Color(0xFF00BB6E).withOpacity(.32);
}
return const Color(0xFF00BB6E);
}),
materialTapTargetSize: MaterialTapTargetSize.padded,
),
);
},
),
],
),
Column(
children: [
const CircleImage(gender: &#39;female&#39;),
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Transform.scale(
scale: 1.5,
child: Checkbox(
value: fIsChecked,
onChanged: (bool? value) {
setState(() {
if (mIsChecked == true) {
mIsChecked = false;
}
fIsChecked = value!;
});
// print(&#39;isChecked: $isChecked&#39;);
},
// activeColor: Colors.green,
fillColor: MaterialStateProperty.resolveWith&lt;Color&gt;(
(Set&lt;MaterialState&gt; states) {
if (states.contains(MaterialState.disabled)) {
return const Color(0xFF00BB6E).withOpacity(.32);
}
return const Color(0xFF00BB6E);
}),
materialTapTargetSize: MaterialTapTargetSize.padded,
),
);
},
),
],
),
],
)
],
),
);
}
}

i have tried using different checks but i thing i'm doing something wrong with the conditional that is why it's not toggling.

答案1

得分: 1

以下是您要翻译的代码部分:

You just have to declare the Boolean values outside the build context. Build context method is called whenever the state is changed. Since you declare and assign values inside the build context function, variables are getting the default value. Also, you don&#39;t need stateful builder.

Full Code : -

import &#39;package:flutter/material.dart&#39;;


void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text(&#39;AlertDialog Sample&#39;)),
        body: const Center(
          child: DialogExample(),
        ),
      ),
    );
  }
}

class DialogExample extends StatefulWidget {
  const DialogExample({super.key});

  @override
  State&lt;DialogExample&gt; createState() => _DialogExampleState();
}

class _DialogExampleState extends State&lt;DialogExample&gt; {
  bool mIsChecked = false;
  bool fIsChecked = false;
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          &#39;BMI Calculator&#39;,
          style: TextStyle(fontSize: 15),
        ),
        centerTitle: true,
        elevation: 0,
      ),
      body: Column(
        children: [
          const Text(
            &#39;I am a &#39;,
          ),
          const SizedBox(height: 50),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Column(
                children: [
                  const Text(
                    &#39;male&#39;,
                  ),
                  Transform.scale(
                    scale: 1.5,
                    child: Checkbox(
                      value: mIsChecked,
                      onChanged: (bool? value) {
                        setState(() {
                          if (fIsChecked == true) {
                            fIsChecked = false;
                          }

                          mIsChecked = value!;
                        });
                        // print(&#39;isChecked: $isChecked&#39;);
                      },
                      // activeColor: Colors.green,
                      fillColor: MaterialStateProperty.resolveWith&lt;Color&gt;(
                          (Set&lt;MaterialState&gt; states) {
                        if (states.contains(MaterialState.disabled)) {
                          return const Color(0xFF00BB6E).withOpacity(.32);
                        }
                        return const Color(0xFF00BB6E);
                      }),
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                    ),
                  )
                ],
              ),
              Column(
                children: [
                  const Text(
                    &#39;female&#39;,
                  ),
                  Transform.scale(
                    scale: 1.5,
                    child: Checkbox(
                      value: fIsChecked,
                      onChanged: (bool? value) {
                        setState(() {
                          print(mIsChecked);
                          if (mIsChecked == true) {
                            mIsChecked = false;
                          }
                          fIsChecked = value!;
                        });
                        setState(
                          () {},
                        );
                        // print(&#39;isChecked: $isChecked&#39;);
                      },
                      // activeColor: Colors.green,
                      fillColor: MaterialStateProperty.resolveWith&lt;Color&gt;(
                          (Set&lt;MaterialState&gt; states) {
                        if (states.contains(MaterialState.disabled)) {
                          return const Color(0xFF00BB6E).withOpacity(.32);
                        }
                        return const Color(0xFF00BB6E);
                      }),
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                    ),
                  )
                ],
              ),
            ],
          )
        ],
      ),
    );
  }
}

Output: -

<img src="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZGRjODFlNDAzYjliMzI5MzI3NzA1Njg5ODQ5OTMyZmRhNjZmMTRhZiZjdD1n/krNUJVjrPjXFYOr66f/giphy.gif">
英文:

You just have to declare the Boolean values outside the build context. Build context method is called whenever the state is changed. Since you declare and assign values inside the build context function, variables are getting the default value. Also, you don't need stateful builder.

Full Code : -

import &#39;package:flutter/material.dart&#39;;
void main() =&gt; runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text(&#39;AlertDialog Sample&#39;)),
body: const Center(
child: DialogExample(),
),
),
);
}
}
class DialogExample extends StatefulWidget {
const DialogExample({super.key});
@override
State&lt;DialogExample&gt; createState() =&gt; _DialogExampleState();
}
class _DialogExampleState extends State&lt;DialogExample&gt; {
bool mIsChecked = false;
bool fIsChecked = false;
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: const Text(
&#39;BMI Calculator&#39;,
style: TextStyle(fontSize: 15),
),
centerTitle: true,
elevation: 0,
),
body: Column(
children: [
const Text(
&#39;I am a &#39;,
),
const SizedBox(height: 50),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: [
const Text(
&#39;male&#39;,
),
Transform.scale(
scale: 1.5,
child: Checkbox(
value: mIsChecked,
onChanged: (bool? value) {
setState(() {
if (fIsChecked == true) {
fIsChecked = false;
}
mIsChecked = value!;
});
// print(&#39;isChecked: $isChecked&#39;);
},
// activeColor: Colors.green,
fillColor: MaterialStateProperty.resolveWith&lt;Color&gt;(
(Set&lt;MaterialState&gt; states) {
if (states.contains(MaterialState.disabled)) {
return const Color(0xFF00BB6E).withOpacity(.32);
}
return const Color(0xFF00BB6E);
}),
materialTapTargetSize: MaterialTapTargetSize.padded,
),
)
],
),
Column(
children: [
const Text(
&#39;female&#39;,
),
Transform.scale(
scale: 1.5,
child: Checkbox(
value: fIsChecked,
onChanged: (bool? value) {
setState(() {
print(mIsChecked);
if (mIsChecked == true) {
mIsChecked = false;
}
fIsChecked = value!;
});
setState(
() {},
);
// print(&#39;isChecked: $isChecked&#39;);
},
// activeColor: Colors.green,
fillColor: MaterialStateProperty.resolveWith&lt;Color&gt;(
(Set&lt;MaterialState&gt; states) {
if (states.contains(MaterialState.disabled)) {
return const Color(0xFF00BB6E).withOpacity(.32);
}
return const Color(0xFF00BB6E);
}),
materialTapTargetSize: MaterialTapTargetSize.padded,
),
)
],
),
],
)
],
),
);
}
}

Output : -

<img src="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZGRjODFlNDAzYjliMzI5MzI3NzA1Njg5ODQ5OTMyZmRhNjZmMTRhZiZjdD1n/krNUJVjrPjXFYOr66f/giphy.gif">

答案2

得分: 0

通常情况下,当您只希望选择一个选项时,使用单选按钮而不是复选框。

这是有关单选按钮类的文档链接:https://api.flutter.dev/flutter/material/Radio-class.html

英文:

Normally you use radio buttons instead of check boxes when you want only one option to be selected.

Here is a link to documentation on the radio class: https://api.flutter.dev/flutter/material/Radio-class.html

huangapple
  • 本文由 发表于 2023年3月31日 20:02:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定