code here constructor's this.colour vairable does not work
class ReusableCard extends StatelessWidget {
Color colour= null;
ReusableCard({@required this.colour});
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: colour,
borderRadius: BorderRadius.circular(10.0),
),
);
}
}
CodePudding user response:
The issue is showing warning message because of null-safety.
On class level Color
is needed to be initialized before read time. In your case you are using named Constructor which is default to act as optional parameter. You can do make it required
on constructor.
final Color colour;
const ReuseableCard({
Key? key,
required this.colour,
}) : super(key: key);
Or make it nullable, as @EnviroApps mentioned. But for this case I prefer like above as my answer.
TO learn more about null-safety
CodePudding user response:
This code should solve your problem:
ReusableCard({this.colour});
Color? colour;
Because Color isnt assigned yet it can be null. Dart has nullsafety so the question mark implies the value can be null. See this link for more details: https://sanjibsinha.com/null-safety-in-flutter-dart/
Edit: you could also do it like this:
ReusableCard({this.colour});
late Color colour;
The late keyword to initialize a variable when it is first read, rather than when it's created