I have used gradient parameter of a Container widget which shows gradient color only if the condition is true if not gradient color is transparent.
Excepted Output : –
If the condition is false then Container widget could be colored by the color passed in the color parameter. In the below code, it is green.
Excepted Output Image : –
Actual Output : –
Transparent gradient color overrides the color given to the color parameter
Actual Output Image : –
Note : – color parameter can have different colors since it also depends on some Boolean flags hence setting the same color to the gradient parameter won’t work.
Code : –
import 'package:flutter/material.dart';
void main() => runApp(const ExampleApp());
class ExampleApp extends StatefulWidget {
const ExampleApp({Key? key}) : super(key: key);
@override
State<ExampleApp> createState() => _ExampleAppState();
}
class _ExampleAppState extends State<ExampleApp> {
bool showGradient = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
showGradient ? Colors.blue : Colors.transparent,
showGradient ? Colors.orange : Colors.transparent,
]),
color: Colors.green[100],
border: Border.all()),
height: 100,
width: 100,
),
)),
);
}
}
>Solution :
Try instead of
gradient: LinearGradient(colors: [
showGradient ? Colors.blue : Colors.transparent,
showGradient ? Colors.orange : Colors.transparent,
]),
do
gradient: showGradient ? LinearGradient(colors: [
Colors.blue,
Colors.orange
]) : null,

