When I try to define the list of colors I get the following message: The element type 'Color?' can't be assigned to the list type 'Color'
return Scaffold(
body: Container(
padding: EdgeInsets.symmetric(vertical:30.0),
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
colors: [
Colors.orange[900],
Colors.orange[800]
]
)
),
),
);
I need help please
CodePudding user response:
When using a subscript to get a color from a ColorSwatch, you will get a Color? which can possibly be a null value. That's because there's no such value as, for example, Colors.orange[1234] - So that would be a null value.
The colors list on the LinearGradient, on the other hand, requires all non-nullable values.
In your case, you're safe simply asserting that the values are non-null, since the colors you're referring to definitely exist:
gradient: LinearGradient(
begin: Alignment.topCenter,
colors: [
Colors.orange[900]!,
Colors.orange[800]!
]
)
You can also avoid the subscripts altogether, like so:
gradient: LinearGradient(
begin: Alignment.topCenter,
colors: [
Colors.orange.shade900,
Colors.orange.shade800,
]
)
Possibly helpful links:
CodePudding user response:
Whenever working with gradients.. i better approach would be to use Colors by providing their hex code.. In flutter when you write Colors. it shows you a list of colors and their shades with their hex code.. https://api.flutter.dev/flutter/material/Colors-class.html
Like in this link. So update your code like this
gradient: LinearGradient( begin: Alignment.topCenter, colors: [ const Color(0xFFE65100), const Color(0xFFEF6C00), ] )
using hex color code is better because their value remain constant and when state is changed that part remains constant (doesn't rebuild)
Do upvote if useful
