Search code examples
androidflutteroopuser-interfacescaffolding

How to access and change a variable from a different file in flutter



I am trying to access and change a variable from a differant file in flutter.
basically, I have created a file called ```colors.dart``` where I'll save the data on the colors that will be used in flutter app.
import 'package:flutter/material.dart';

class colors {
  static Color bgColor = Color(0xfff8f8f8);
}

And I wish to change its value when I press on a button
I imported the dart file in my new file and iniside the onpressed function of my button I have:


MaterialApp(
      home: Scaffold(
        backgroundColor: colors.bgColor,
...

onPressed: () {
      setState(() {
    colors.bgColor = Color(0xff313131);
  });
},

The color inside of bgColor.dart does show up but when I try to change it onPressed (also in an stateful widget) it does not change the scaffold color


Solution

  • If scaffold and button are in the same stateful widget

    First of all make sure that backgroundColor: colors.bgColor and setState both are in the same stateful widget, it should work(tested)

    If scaffold and button are in different widgets

    this way is not dependent on setState so you can use it in both stateless and stateful widgets

    1. Change type of color to ValueNotifier<Color>,

    optional: name types using UpperCamelCase

    class CustomColors {
      static ValueNotifier<Color> bgColor = ValueNotifier(const Color(0xfff8f8f8));
    }
    
    1. wrap scaffold with a ValueListenableBuilder and access color with value property
        MaterialApp(
          home: ValueListenableBuilder<Color>(
            valueListenable: CustomColors.bgColor,
            builder: (context, value, child) => Scaffold(
              backgroundColor: value,
    
    
    1. to change color:
    onPressed: () {
        CustomColors.bgColor.value = Colors.red;
    }