3

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?

rozerro
  • 5,787
  • 9
  • 46
  • 94
  • 2
    check this https://github.com/flutter/flutter/issues/27733 – John Joe Oct 18 '20 at 06:10
  • 1
    You can have a look at the following answer: https://stackoverflow.com/questions/56494710/color-shades-are-not-constant-values-in-flutter#:~:text=When%20you%20use%20Colors.,a%20shade%20instead%2C%20i.e.%20Colors.&text=This%20is%20important%2C%20for%20example,default%20value%20must%20be%20constant. – Robert Sandberg Oct 18 '20 at 06:18
  • @RobertSandberg well, it's arguable what's easy to use - Color(0xFF42A5F5) or just final keyword :) – rozerro Oct 18 '20 at 06:23
  • We'll, using final isn't an answer to the question, final and const isn't the same thing. – Robert Sandberg Oct 18 '20 at 07:13
  • 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 Oct 18 '20 at 08:32

1 Answers1

3

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];
thomas.s
  • 308
  • 1
  • 3
  • 14