2
votes

When I do something like this

import 'package:flutter/material.dart';

const kBaseColor = Colors.deepPurple;
const kBase300 = Colors.deepPurple[300]; // there is an error

error: Const variables must be initialized with a constant value. (const_initialized_with_non_constant_value at [myprogect] lib\ui\widgets\constants.dart:4)

Isn't it possible to assign a shade of the color as const variable?

1
You can have a look at the following answer: stackoverflow.com/questions/56494710/…. - Robert Sandberg
@RobertSandberg well, it's arguable what's easy to use - Color(0xFF42A5F5) or just final keyword :) - rozerro
We'll, using final isn't an answer to the question, final and const isn't the same thing. - Robert Sandberg
Because he explicitly asked for a const variable. I'm not saying that using final isn't a viable option depending on use case. Given the information it isn't clear that he wanted to know because of a particular use case or just to increase his understanding. - Robert Sandberg

1 Answers

2
votes

you can use final instead of that, the reason is If the value you have is computed at runtime you can not use a const for it. you can use final instead of that like this

final kBase300 = Colors.deepPurple[300];