Nilton Schumacher F
Nilton Schumacher F

Reputation: 27

Creating a Color Class in flutter

I'm trying to create a color class in Flutter, My main objective, is that I will be able to access the colors from this class anywhere and change them when I need.
I have attempted to create like this, but I can't seem to access the variables:

import 'package:flutter/material.dart';

class ColorSelect {

  Color cbuttons = const Color(0xFF1520A6);
  //there will be other colors here
}

This is how I tried to get the color:

 child: Text(
                  userManager.isLoggedIn ? 'Sair' : 'Entre ou cadastre-se >',
                  style: TextStyle(
                    color: ColorSelect.cbuttons,
                    fontWeight: FontWeight.bold
                  ),
                ),

but accessing the color class like this didn't work.

Upvotes: 1

Views: 6857

Answers (4)

DevMukh
DevMukh

Reputation: 29

    import 'package:flutter/material.dart';
    class ColorsField{
      static const buttonColor=Color(0xFF1520A6);
      static const textcolor=Color(your color);
      static const background=Color(your color);
      static const headingColor=Color(your color);
    }
Make this static so you can able to access 

Upvotes: 0

Divyesh mehta
Divyesh mehta

Reputation: 464

let me suggest you better way then the Color Class follow the steps

Step:1 create a dart file name eg. Colors.dar and in your Colors.dart add the color as const like below first import flutter material package.

import 'package:flutter/material.dart';

Step:2 define color which you want like below and Save the file

const MainBackgroundColor = const Color(0xff27a6c3);

Step:3 now use it you just have to import the file and use like below

import 'package:flutter/material.dart'; 
import 'Colors.dart'; 

 /// here set the color of containe 
 
 Container(
     height: 100.0,
     width: 100.0,
     color: MainBackgroundColor,
    ),

you also define your all colors here in this file and use allover in your app using this way and it is very easy to manage your theme.

Upvotes: 0

nicks101
nicks101

Reputation: 1191

Extending the answer from the comments.

I think you're confused about the concept of classes in dart (or any OOP language for that matter).

To access a property of a class, you have to instantiate it.

color: ColorSelect().cbuttons,

or use static properties.

class ColorSelect {

 static Color cbuttons = const Color(0xFF1520A6);
}

I'll encourage you to research this.

Upvotes: 1

eeqk
eeqk

Reputation: 3862

Add static keyword:

import 'package:flutter/material.dart';

class ColorSelect {
  static final cbuttons = const Color(0xFF1520A6);
}

Upvotes: 3

Related Questions