Search code examples
androidflutterdartflutter-layouthybrid-mobile-app

flutter checkbox not working in StatelessWidget


Here is my class

class Home extends StatelessWidget {

and the Checkbox goes here.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(20.0),
              child: Column(
                children: <Widget>[
                  TextField(
                      controller: ctrlMotherName,
                      decoration: InputDecoration(
                          labelText: "Name of Mother",
                          border: OutlineInputBorder()
                      )
                  ),
                  SizedBox(height: 10,),
                  Checkbox(
                    value: false,
                    onChanged: (bool val){

                    },
                  ),

I can't able to check the checkbox. Same issue found when I use Radiobutton also.


Solution

  • You need to use a StatefulWidget since you're dealing with changing values. I've provided an example:

    class MyAppOne extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyAppOne> {
      bool _myBoolean = false;
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Checkbox(
            value: _myBoolean,
            onChanged: (value) {
              setState(() {
                _myBoolean = value; // rebuilds with new value
              });
            },
          ),
        );
      }
    }