skip to Main Content

I am learning custom widget for reusable..

here i want to make a container with default light color of grey but while applying Colors.grey.shade200 its showing error

looks like Colors.grey is constant but .shade200 is not constant value

so how can we use shade of color as constant …

class RoundedContainer extends StatelessWidget {
  
  final Color backgroundColor;
 

  const RoundedContainer({
    super.key,
    
    this.backgroundColor= Colors.grey.shade200,//showing error
   
  });

2

Answers


  1. You cannot do above because: Colors.grey.shade200 value is not a compile-time constant. You can do it like this you can make the backgroundColor nullable and later assign the shade if the color is not available.

    class RoundedContainer extends StatelessWidget {
      final Color? backgroundColor;
    
      
      const RoundedContainer({
        Key? key,
        required this.backgroundColor,
      }) : super(key: key);
    
     
    
      @override
      Widget build(BuildContext context) {
        // Rest of your build method
        return Container(
          color: backgroundColor ?? Colors.grey.shade200
        );
      }
    }
    
    Login or Signup to reply.
  2. default value should be const. Colors.grey.shade200 is not a const and you can’t set it as default. what you can do instead of this is to make this color nullable and set value if it is null:

    class RoundedContainer extends StatelessWidget {
         
      const RoundedContainer({
        this.backgroundColor,
        super.key,
      });
    
      final Color? backgroundColor;     
    
      @override
      Widget build(BuildContext context) {
        final bg = backgroundColor ?? Colors.grey.shade200;
        ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search