skip to Main Content

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<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 have tried using different checks but i thing i’m doing something wrong with the conditional that is why it’s not toggling.

2

Answers


  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’t need stateful builder.

    Full Code : –

    import 'package:flutter/material.dart';
    
    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('AlertDialog Sample')),
            body: const Center(
              child: DialogExample(),
            ),
          ),
        );
      }
    }
    
    class DialogExample extends StatefulWidget {
      const DialogExample({super.key});
    
      @override
      State<DialogExample> createState() => _DialogExampleState();
    }
    
    class _DialogExampleState extends State<DialogExample> {
      bool mIsChecked = false;
      bool fIsChecked = false;
      @override
      Widget build(BuildContext context) {
        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: [
              const Text(
                'I am a ',
              ),
              const SizedBox(height: 50),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Column(
                    children: [
                      const Text(
                        'male',
                      ),
                      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 Text(
                        'female',
                      ),
                      Transform.scale(
                        scale: 1.5,
                        child: Checkbox(
                          value: fIsChecked,
                          onChanged: (bool? value) {
                            setState(() {
                              print(mIsChecked);
                              if (mIsChecked == true) {
                                mIsChecked = false;
                              }
                              fIsChecked = value!;
                            });
                            setState(
                              () {},
                            );
                            // 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,
                        ),
                      )
                    ],
                  ),
                ],
              )
            ],
          ),
        );
      }
    }
    

    Output : –

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search