flutter checkbox not working in StatelessWidget

橙三吉。 提交于 2021-01-28 19:10:30

问题


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.


回答1:


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
          });
        },
      ),
    );
  }
}


来源:https://stackoverflow.com/questions/59438186/flutter-checkbox-not-working-in-statelesswidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!