Andrea_Fox
Andrea_Fox

Reputation: 13

Flutter pass a value to a global variable

i am using flutter and stackoverflow for the first time, forgive me errors. I have global variables in a global.dart file. In my main I want to access and edit a variable by passing it the value

Global.dart
String nome_impianto1 = "IMPIANTO 1";
String nome_impianto2 = "IMPIANTO 2";
String nome_impianto3 = "IMPIANTO 3";
String nome_impianto4 = "IMPIANTO 4";

main.dart
import 'package:services/global.dart' as globals;
globals.nome_impianto1 = usrcontroller_ovrelay_impianto.text;  //so it works.

how can I pass the value I want to change?

globals.nome_impianto{$'1'} = usrcontroller_ovrelay_impianto.text //I know it doesn't work, and just to get the idea;

thank to all Best regards Andrea

Upvotes: 1

Views: 6698

Answers (2)

Phani Rithvij
Phani Rithvij

Reputation: 4477

  1. Avoid using global variables in flutter. If you are managing state gloabally use StatefulWidget and even better start using provider or even more advanced bloc.

  2. For your question, if you want to access these globally it is better to use a Map

//  Global.dart
  Map<String, String> globals = {
    "nome_impianto1": "IMPIANTO 1",
    "nome_impianto2": "IMPIANTO 2",
    "nome_impianto3": "IMPIANTO 3",
    "nome_impianto4": "IMPIANTO 4",
  };

// main.dart
  int index = 1;
  globals["nome_impianto$index"] = usrcontroller_ovrelay_impianto.text;
  1. flutter doesn't have reflection https://stackoverflow.com/a/49871692/8608146

Upvotes: 2

Z. Cajurao
Z. Cajurao

Reputation: 375

Add this to any of your function:

 setState((){
      globals.nome_impianto1 = usrcontroller_ovrelay_impianto.text;
    });

Upvotes: 0

Related Questions