Home > Mobile >  Getting a new variables from a function
Getting a new variables from a function

Time:10-05

I have 3 files

Main which contains a function call when the application is launched

void main() async { 
  await FunctionCall().numberColumnFunction();
  runApp(const MyApp());
}

Function in which the called function and variables are located:

class FunctionCall {
    
  int numberColumn = 3;

  int columnsPositioned = 5;
  var visibilityColumn = false;

    numberColumnFunction(){
      if (numberColumn == 3) {
        columnsPositioned = 8;
        visibilityColumn = true;
      }
      else {
        null;
      }
    }
}

And ColumnView in which I get variables from the Function for further work with them:

// More code
     end: width / FunctionCall().columnsPositioned,
// More code
     visible: FunctionCall().visibilityColumn,
// More code

The problem is that in ColumnView the variables declared by me with default values are always called

  int columnsPositioned = 5;
  var visibilityColumn = false;

Even if the function conditions are met and the values in the variables change, the call still goes to the old values. How do I make ColumnView take values after executing the function ?

CodePudding user response:

The traditional and programming way I can think of right now is making that class a singleton. You can search and do more research on singleton classes and factory pattern. But for now, this code should solve your problem ->

class FunctionCall {
 FunctionCall._sharedInstance(); //This is a private constructor. 
 static final FunctionCall _shared = FunctionCall._sharedInstance(); // This is the instance we want to send every time.
 factory FunctionCall() => _shared; // This is where we send it every time the class is created!

 int numberColumn = 3;
 int columnsPositioned = 5;
 var visibilityColumn = false;

numberColumnFunction(){
  if (numberColumn == 3) {
    columnsPositioned = 8;
    visibilityColumn = true;
  }
  else {
    null;
    }
  }
}

Basically, the problem was, Every time you called the class like this FunctionCall() It was creating a new class. And a new class would always have the default class data. Bcz the function didn't get called inside the new class. So to stop making a new instance of your class you can try this way of making your class a singleton. And returning the exact same instance of your class when it is initiated! And Done!

CodePudding user response:

You are creating the FunctionCall() object inside the main function. The Visibility Column for this object is true. However, you are creating a new FunctionCall() object inside the ColumnView widget. The visibilityColumn value of this object is initially set to false. They are two different objects.

My suggestion:

FunctionCall functionCall = FuncitonCall();

Define the above code globally. Edit this object in main and use the same object in ColumnView widget.

  • Related