Search code examples
flutterdartopacity

Flutter using ".withOpacity" leads to "the field is initialized with a non constant value"


I have an own class for my app-colors:

import 'package:flutter/material.dart';

@immutable
class AppColors {
  final objectRow=const Color(0xFFFFFFFF).withOpacity(0.5);

  const AppColors();

}

If I don't use .withOpacity the constructor can be const but if I use it I have to delete the const. I don't understand why... Please explain to me why the opacity can't be known at compile-time


Solution

  • In the code above const Color(0xFFFFFFFF) is a constant, but withOpacity(0.5) creates a new Color value at runtime with a different opacity.

    You don't need to call withOpacity to adjust the opacity of the color, since the first two hexadecimal digits in the color already refer to the opacity. You can achieve the desired result by adjusting those digits const Color(0x80FFFFFF).