Home > OS >  how to enable checkbox with tapping on text in flutter?
how to enable checkbox with tapping on text in flutter?

Time:10-22

I have a checkbox with a text next to the checkbox I want when user tap on text the checkbox be enable/disable, how can i do that?

  Widget buildRememberCb() {
    return Container(
      height: 200,
      child: Row(
        textDirection: TextDirection.rtl,
        children: [
          Theme(
            data: ThemeData(unselectedWidgetColor: Colors.white),
            child: Checkbox(
              value: isRememberMe,
              checkColor: Color(0xfff44336),
              activeColor: Colors.white,
              onChanged: (value) {
                setState(() {
                  isRememberMe = value!;
                });
              },
            ),
          ),
          Text(
            "Remember Me",
            style: TextStyle(
                fontWeight: FontWeight.w900, fontSize: 18, color: Colors.white),
          ),
        ],
      ),
    );
  }

CodePudding user response:

Wrap the Text with GestureDetector and change the value of isRememberMe in onTap,

  Widget buildRememberCb() {
    return Container(
      height: 200,
      child: Row(
        textDirection: TextDirection.rtl,
        children: [
          Theme(
            data: ThemeData(unselectedWidgetColor: Colors.white),
            child: Checkbox(
              value: isRememberMe,
              checkColor: Color(0xfff44336),
              activeColor: Colors.white,
              onChanged: (value) {
                setState(() {
                  isRememberMe = value!;
                });
              },
            ),
          ),
          GestureDetector(
            onTap: (){
              setState((){
                isRememberMe = isRememberMe ? false : true;
              });
            },
            child: Text(
              "Remember Me",
              style: TextStyle(
                fontWeight: FontWeight.w900, fontSize: 18, color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

If you want an Ink splash you could replace the GestureDetector with InkWell but a better approach to that would be to just use TextButton,

TextButton(
  onPressed: () {
    setState((){
      isRememberMe = isRememberMe ? false : true;
     });
  },
  child: Text(
    "Remember Me",
    style: TextStyle(
      fontWeight: FontWeight.w900, 
      fontSize: 18, 
      color: Colors.white,
    ),
  ),
),
  • Related