5

When developing app with flutter, i want to define some common styles.

The code is as follows:

import 'package:flutter/material.dart';
class AppStyle {
  static Color colorRed = const Color(0xffe04f5f);
  static Color colorWhite = const Color(0xffffffff);
  static Color colorGreen = const Color(0xff1abc9c);
}

Now, i want to define a new style.

static TextStyle listRowTitle = const TextStyle(fontSize: 20.0, color: colorGreen);

If you write to the above, then colorGreen will have a problem here. The wrong message is

[dart] Invalid constant value.
[dart] Arguments of a constant creation must be constant expressions.
Color colorGreen

If you change colorGreen to Color (0xff1abc9c), there is no problem!

static TextStyle listRowTitle = const TextStyle(fontSize: 20.0, color: Color(0xff1abc9c));

Ask me to teach me,please!

sunmoon
  • 355
  • 1
  • 4
  • 8

2 Answers2

3

Since, colors are defined in a class you have to do something like below:

AppStyle.colorGreen

Udate:

Ohh, I see, you are using cont TextStyle. So, you can remove const or add const for your AppStyle.

I simply removed the const from TextStyle:

TextStyle(fontSize: 20.0, color: AppStyle.colorGreen)

Understand how const works.

Blasanka
  • 21,001
  • 12
  • 102
  • 104
  • Thank you for your answer,and i tried like you, but there are have a problem。static TextStyle listRowTitle = const TextStyle(fontSize: 20.0, color: AppStyle.colorGreen); The error message :[dart] Invalid constant value. class AppStyle – sunmoon Oct 26 '18 at 01:27
  • Thank you. My problem has been solved. I think I should go deeper into the grammar of dart. Finally, can you help me explain why? – sunmoon Oct 26 '18 at 01:58
  • @sunmoon you have to understand `const` and `new` read this https://stackoverflow.com/questions/47996420/what-color-system-does-flutter-use-and-why-do-we-use-const-color-instead-of-n – Blasanka Oct 26 '18 at 02:00
  • 1
    The problem is you are declaring a variable value (colorGreen) to a property (color) of a constant widget. Constant widgets cannot vary, change. – egidiocs Jan 24 '20 at 21:37
0

The problem is you are declaring a variable value (colorGreen) to a property (color) of a constant widget. Constant widgets cannot vary, change.

Just remove the modifier const from your widget

static TextStyle listRowTitle = const TextStyle(fontSize: 20.0, color: colorGreen);
egidiocs
  • 2,747
  • 3
  • 21
  • 20