Reputation: 147
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;
},
);
}
}
Upvotes: 2
Views: 195
Reputation: 2324
You can call setState()
like this:
setState(() {
isChecked = !isChecked;
});
Upvotes: 1
Reputation: 21
The toggleCheckBoxState
is a function without parameter, which is why the state is not changing in the checkBoxCallback
as the parameter checkBoxState
did not have a value.
To fix it, you should change the TaskCheckBox
as follow:
class TaskCheckBox extends StatefulWidget {
late final bool checkboxState;
final Function(bool?) 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(value);
},
);
}
}
Upvotes: 1
Reputation: 14785
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!;
});
},
),
),
Upvotes: 1