Search code examples
flutterdartflutter-theme

Can't use a custom class/color to set the color value of scaffoldBackgroundColor


I've created a custom set of colors to reuse in a Flutter app, but I'm getting an error when I try to use the colors to set the scaffoldBackgroundColor color value.

The argument type 'UIColor' can't be assigned to the parameter type 'Color?

But I can use the class for other parameters where color is the required type

import 'package: flutter/material.dart';

class UIColor { //extends Color {
  UIColor._();

  static const int _jetBlackPrimaryValue = 0xFF141414;
  static const Color jetBlack = Color(_jetBlackPrimaryValue);

  static const int _flashWhitePrimaryValue = 0xFFf0f0f0;
  static const Color flashWhite = Color(_flashWhitePrimaryValue);

  static const int _spaceBluePrimaryValue = 0xFF142850;
  static const Color spaceBlue = Color(_spaceBluePrimaryValue);

  static const int _magentaPrimaryValue = 0xFF8c3c64;
  static const Color magenta = Color(_magentaPrimaryValue);

  static const int _sodaPrimaryValue = 0xFFf0643c;
  static const Color soda = Color(_sodaPrimaryValue);

  static const int _creamPrimaryValue = 0xFFffc88c;
  static const Color cream = Color(_creamPrimaryValue);
  
}

The UIColor can't be used for scaffoldBackgroundColor but can for other settings requiring a class/type of color

 title: 'Sim Town',
      darkTheme: ThemeData.dark().copyWith(
          scaffoldBackgroundColor: UIColor.jetBlack, // Color(0xFF141414), //Color(0xFFf0f0f0),
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          tabBarTheme: const TabBarTheme(
              labelColor: UIColor.cream,
              unselectedLabelColor: UIColor.flashWhite,
              indicator: UnderlineTabIndicator(
                  // color for indicator (underline)
                  borderSide: BorderSide(color: UIColor.flashWhite)))),


Solution

  • I ran your code, here's what I found:

    • You need to remove the const keyword.

    Since your using .copyWith(...), you are creating a new instance of ThemeData at runtime, which isn't a compile-time constant.

    Change:

    ThemeData.dark().copyWith(
            scaffoldBackgroundColor: const UIColor.flashWhite,
          ),
    

    To:

    ThemeData.dark().copyWith(
            scaffoldBackgroundColor: UIColor.flashWhite, // --> Remove `const`.
          ),