skip to Main Content

I’d like to make an external dart file (let’s call it color_palette.dart), that have some classes of colors. These classes would be able to be changed by a menu on another page of the app. These colors would be used in all the pages to define the colors of Appbar, buttons, icons, etc…
I don’t want to use the theme() for it.
I want to use some functions that can be used in a button (onPress : function) to change the colors.

Here is an example :

color_palette.dart

class myColor {
return Colors.red;
}

mainpage.dart

Scaffold(
appbar : AppBar(
  color : MyColor(),
  )
)

2

Answers


  1. There are many ways to do that:

    First method:

    // in the file where you define constants
    import 'package:flutter/material.dart'; 
    const Color color_red = Colors.red;
    
    // in the file where you want to use it
    Scaffold(
    appbar : AppBar(
      color : color_red,
      )
    )
    

    The second method, Using a color class.

    class Palette {
      static const Color color_red = Colors.red;
    }
    
    //in the file where you want to use it:
    
    import "package:app_name/folder_name/palette.dart";
    Scaffold(
    appbar : AppBar(
      color : Palette.color_red,
      )
    )
    
    Login or Signup to reply.
  2. very easy to do

        void main() {
          
          //change color A from red to purple
          MyColors.colorA = Colors.purple;
              
        }
        
        class MyColors {
          static Color colorA = Colors.red;
          static Color colorB = Colors.green;
          static Color colorC = Colors.blue;
        }
    

    Scaffold(
    appbar : AppBar(
      color : MyColors.colorA,
      )
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search