I’m a beginner to flutter please someone help!
Error: A value of type ‘bool?’ can’t be assigned to a variable of type ‘bool’ because ‘bool?’ is nullable and ‘bool’ isn’t.
color: isDone ? Color(0xFF7349FE) : Colors.transparent,
class TodoWidget extends StatelessWidget {
final String? text;
final bool? isDone;
TodoWidget({this.text, @required this.isDone});
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: 24.0,
vertical: 8.0,
),
child: Row(
children: [
Container(
width: 20.0,
height: 20.0,
margin: EdgeInsets.only(
right: 12.0,
),
decoration: BoxDecoration(
color: isDone ? Color(0xFF7349FE) : Colors.transparent,
borderRadius: BorderRadius.circular(6.0),
),
child: Image(
image: AssetImage(
'assets/images/check_icon.png'
),
),
),
Text(
text ??"(Unnamed Todo)",
style: TextStyle(
color: Color(0xFF211551),
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
],
),
);
}
}
3
Answers
Dart is a language which uses null safety. When you declaring
bool? isDone;
you are giving?
here. It meansisDone
boolean can be null ( It means it can containnull
other thantrue
orfalse
).So, when you are using this variable in a condition which only acceptstrue
orfalse
it may providenull
.So, here the best thing to do is gave a default value to the
isDone
variable. Likebool isDone = false;
. Don’t forgot to remove?
.Don’t forgot to gave tick if you find this helpful. Any doubts comment.
Just change this:
Before:
bool? isDone;
After:
bool isDone = false;
orbool isDone = true
. It depends on your purpose.A todo will always be done or not-done, there’s no case where a todo can be neither.
So instead of keeping
isDone
nullable, keep a default value for isDone. This way you only have to code the widget fortrue
orfalse
cases, and not for thenull
case.change the declaration to make it non-nullable:
change the constructor to make it false by default: