Home > Back-end >  how to access declared variables from another class on Flutter
how to access declared variables from another class on Flutter

Time:12-15

I have a class called FontSize that has a declared variable in it. Then I want to access these variables on multiple other classes. when I tried to call it on another class it shows a compile-time error that says "the variable is not declared". I am using flutter v2.5.

CodePudding user response:

Put static in front of that variable, for example :

class Constant {
  static Color color = Color.fromARGB(255,0,153,0);
}

You can access it with Constant.color

CodePudding user response:

You can declare and use varibale using below both methods

class AppFontSize {
  static double smallSize = 11.0;
  static double mediumSize = 14.0;
  static double largeSize = 19.0;
}

// Use this variable like

Text(
      "Hello Demo",
      style: TextStyle(fontSize: AppFontSize.smallSize),
    ),

OR

const double smallSize = 11.0;
const double mediumSize = 14.0;
const double largeSize = 19.0;

 // Use this variable like
    
Text(
      "Hello Demo",
      style: TextStyle(fontSize: smallSize),
    ),

It work and useable for you then please upvote me. Thanks

CodePudding user response:

Define variable as static in one class in a flutter.

class Something {
   static int counter; 
}

Just import that class into the other class you want to access as:

import 'package:your_projectname/your_folder/name.dart';

You can access that variable in another class as:

class StatefulWidget{
   FlatButton(
    onPressed: (){
      Something.counter  ; // This variable is your counter you mentioned earlier
   }
);
}
  • Related