简体   繁体   中英

How can i access to a variable in main.dart to other pages in flutter, i am using Getx state management

How can I access a variable in main.dart to other pages in flutter with Getx state management, Here I want to make the localMemberid in main.dart as Global to access from anywhere or pass it to other pages and is it the right way to use secure storage for storing the data

main.dart

void main() {
  SecureStorage secureStorage = SecureStorage();
  var localMemberid; // i would like to make this varial global or pass this value to other pages

  runApp(
    ScreenUtilInit(
      builder: (BuildContext context, Widget? child) {
        return GetMaterialApp(
          title: "onyx",
          initialRoute: AppPages.INITIAL,
          getPages: AppPages.routes,
          theme: ThemeData(primarySwatch: MaterialColor(0xFF0456E5, color)),
        );
      },
    ),
  );

  SecureStorage.readLocalSecureData('memberid')
      .then((value) => localMemberid = value);
}

Login Controller

class LoginController extends GetxController {
  final AuthenticationRepo _authRepe = AuthenticationRepo();
  final SecureStorage secureStorage = SecureStorage();
  String? localMemberid; // i would like to get the localMemberid from the main.dart

  //TODO: Implement LoginController

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}

  var userid;
  var password;
  
 

  onSinginButton() async {
    var res = await _authRepe.login(username: userid, password: password);
    if (res.status == ApiResponseStatus.completed) {
      print(res.data);
      await SecureStorage.writeLocalSecureData('memberid', res.data!.memberid);
      localMemberid == null
          ? Get.toNamed(Routes.LOGIN)
          : Get.toNamed(Routes.HOME);
    } else {
      Get.defaultDialog(title: res.message.toString());
    }
  }
}

Uplift your variable from the main function and make it Rx:

  var localMemberid=Rxn<String>(); // i would like to make this varial global or pass this value to other pages

void main() {
     SecureStorage secureStorage = SecureStorage();

     .......

   SecureStorage.readLocalSecureData('memberid')
      .then((value) => localMemberid.value = value);
   }

And then on your LoginController remove String? localMemberid; // String? localMemberid; // String? localMemberid; // and import main.dart :

localMemberid.value == null
      ? Get.toNamed(Routes.LOGIN)
      : Get.toNamed(Routes.HOME);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM