Manraj Singh
Manraj Singh

Reputation: 110

A value of type 'Color?' can't be assigned to a variable of type 'Color'

Trying to pass a default value for background color to the constructor but these are the error messages popping up. I have tried using Colors.red[200]! and Colors.red.shade200 but none of those worked out.

import "package:flutter/material.dart";

class Category {
  final String id;
  final Color bgColor;
  final String title;

  Category(
    {required this.id, required this.title, this.bgColor = Colors.red[200]});
}

enter image description here

Upvotes: 1

Views: 2045

Answers (2)

Jigar Patel
Jigar Patel

Reputation: 5423

Change to this.

this.bgColor = const Color(0xFFEF9A9A)

The error is becuase, like the error says - The default value of an optional parameter must be a constant. And Colors.red[200] is not a constant but const Color(0xFFEF9A9A) is.

Upvotes: 1

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14885

You should try this following answer :

class Category {
  Category({
    @required this.id,
    @required this.title,
    this.bgColor: const Color(0xFFEF9A9A),
  });
  final String id;
  final Color bgColor;
  final String title;
}

Upvotes: 1

Related Questions