CheckBox not getting ticked

Issue

I am making a List App which a list of items followed by a checkBox .When i run the app the checkBox dosent seem to change the state .It is inactive .
I am using the flutter sdk version 2.12.0 with null safety.

Here is my Code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class TaskTile extends StatefulWidget {
   const TaskTile({ required this.text});
  final Text text;
  @override
  State<TaskTile> createState() => _TaskTileState();
}
class _TaskTileState extends State<TaskTile> {
  bool isChecked = true;
  void checkBoxCallBack(bool checkBoxState)
  {
    setState((){
      isChecked = checkBoxState;
    });
  }
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text('This is task',
      style:TextStyle(
        decoration:  isChecked ? TextDecoration.lineThrough:null),
      ),
      trailing:  TaskCheckBox(isChecked, checkBoxCallBack),
    );
  }
}
class TaskCheckBox   extends StatefulWidget {
  late final bool checkboxState;
  final Function toggleCheckBoxState;
  TaskCheckBox(this.checkboxState, this.toggleCheckBoxState);

  @override
  State<TaskCheckBox> createState() => _TaskCheckBoxState();
}

class _TaskCheckBoxState extends State<TaskCheckBox> {
  @override
  Widget build(BuildContext context) {
    return Checkbox(
    value:(widget.checkboxState),
    activeColor:Colors.lightBlueAccent,
      onChanged: (bool? value) {
      widget.toggleCheckBoxState;
      },
    );
  }
}

Solution

Try below Code hope its help to you.

Declare bool variable

bool isChecked = false;

Your Widget

   ListTile(
        title: Text(
          'This is task',
          style: TextStyle(
              decoration: isChecked ? TextDecoration.lineThrough : null),
        ),
        trailing: Checkbox(
          checkColor: Colors.white,
          value: isChecked,
          onChanged: (bool? value) {
            setState(() {
              isChecked = value!;
            });
          },
        ),
      ),

Your Result before check-> enter image description here

Your Result after check-> enter image description here

Answered By – Ravindra S. Patil

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.