Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to override gradient color parameter of Container widget with color parameter

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Excepted Output Image : –

enter image description here

Actual Output : –

Transparent gradient color overrides the color given to the color parameter

Actual Output Image : –

enter image description here

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,
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading