When creating this stateless widget I try to assign a TextDecoration value to a widget attribute based on the value of a boolean attribute from the object being passed to it on creation.
textDecoration = item.isComplete ? TextDecoration.lineThrough : TextDecoration.none,
On this row it marks item.isComplete
as an error, saying invalid constant value.
Is it because isComplete
in the class is defined with the late
keyword and therefore it could be null? I checked all the possible causes for which the invalid constant value error migh arise and I still haven't made any sort of dent into it.
The widget:
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import '../models/grocery_item.dart';
class GroceryTile extends StatelessWidget {
final GroceryItem item;
final Function(bool?)? onComplete;
final TextDecoration textDecoration;
const GroceryTile({
Key? key,
required this.item,
this.onComplete,
}) : textDecoration = item.isComplete // Error here
? TextDecoration.lineThrough
: TextDecoration.none,
super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
The class:
import 'package:flutter/painting.dart';
enum Importance { low, medium, high }
class GroceryItem {
final String id;
final String name;
final Importance importance;
final Color color;
final int quantity;
final DateTime date;
late bool isComplete;
GroceryItem({
required this.id,
required this.name,
required this.importance,
required this.color,
required this.quantity,
required this.date,
this.isComplete = false,
});
GroceryItem copyWith({
String? id,
String? name,
Importance? importance,
Color? color,
int? quantity,
DateTime? date,
bool? isComplete,
}) {
return GroceryItem(
id: id ?? this.id,
name: name ?? this.name,
importance: importance ?? this.importance,
color: color ?? this.color,
quantity: quantity ?? this.quantity,
date: date ?? this.date,
isComplete: isComplete ?? this.isComplete);
}
}
The const constructor cannot have a body and if you want to initialize some value in the constructor body you need to remove the const
keyword
//...
GroceryTile({ // <- Remove `const`here
Key? key,
required this.item,
this.onComplete,
}) : textDecoration = item.isComplete
? TextDecoration.lineThrough
: TextDecoration.none,
super(key: key);
//...