Home > OS >  how do i access the value in the function
how do i access the value in the function

Time:06-01

I'm new to flutter, I want to access the value inside the function from within the class. How can I provide this? The select I am trying to Select value. Thank you for your answers.

 Widget levelsec() {
   String select= "Level Sec";
}

CodePudding user response:

If you declare the variable in the function, it can only be accessible within the function. It is scoped to the function. Each new set of curly braces adds a new scope. Inner scopes can reach outer, but not vice versa.

If you want to assign the variable in the function, and then reach the value outside the function, you'd have to declare it outside the function or return it from the function.

Example:

class Foo {
  String? select;

  void levelsec() {
    select = "Level Sec";
  }

  void doStuff() {
    print(select); // Can reach the variable
  }
}

CodePudding user response:

In addition to Robert's answer, you can also return the needed value from the function.

In your example, you have declared a function like this:

Widget levelsec() {
  String select= "Level Sec";
}

As we see, your function starts with Widget, so it is the expected return type. But if you need a string value from that particular function, you should return the String. To achieve this, you must start to declare your "function" by writing String. So in the end, it will look like this:

String levelsec() {
   final String select = "Level Sec";
   return select;
}

Short version:

String levelsec() => "Level Sec";

Please note: If you need to access not only a single value but many, you should consider declaring them globally. Because if you declare a variable in a function, it is accessible only in the scope of that function.

  • Related