I am getting error while trying to pass bool value to the TaskCheckbox() method. I am new to flutter and any help would be much appreciated
class _TaskTileState extends State<TaskTile> {
bool? isChecked = false;
@override
Widget build(BuildContext context) {
return const ListTile(
title: Text('This is a task'),
trailing: TaskCheckbox(isChecked),
);
}
}
class TaskCheckbox extends StatelessWidget {
final bool? checkboxState;
const TaskCheckbox(this.checkboxState, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Checkbox(
value: checkboxState,
onChanged: (newValue) {},
);
}
}
CodePudding user response:
You need to remove const
before ListTile
because the value will get on runtime.
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('This is a task'),
trailing: TaskCheckbox(isChecked),
);
}
const
keyword used to make a variable to store a compile time constant value. Compile time constant value is a value which will be constant while compiling , ref
CodePudding user response:
You need to use Stateful Class
widget for the build checkbox because we need to use setState for changing value inside the checkbox.
Use this code. This work fine for me:
class TaskTileState extends StatefulWidget {
@override
_TaskTileState createState() => _TaskTileState();
}
class _TaskTileState extends State<MyHomePage> {
bool? isChecked = true;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('This is a task'),
trailing: TaskCheckbox(isChecked),
);
}
}
class TaskCheckbox extends StatefulWidget {
final bool? checkboxState;
const TaskCheckbox(this.checkboxState, {Key? key}) : super(key: key);
@override
State<TaskCheckbox> createState() => _TaskCheckboxState();
}
class _TaskCheckboxState extends State<TaskCheckbox> {
bool? isChecked;
@override
void initState() {
isChecked = widget.checkboxState;
}
@override
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
return Checkbox(
checkColor: Colors.black,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
);
}
}
Related from @Yeasin Sheikh's answer, you do have to remove the const
in the ListView