[英]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如何使用 Getx 状态管理将 main.dart 中的变量访问到其他页面,在这里我想将 main.dart 中的 localMemberid 设置为全局,以便从任何地方访问或将其传递给其他页面,这是正确的方法吗?使用安全存储来存储数据
main.dart
主要.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:从主函数中提升您的变量并使其成为 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; //
然后在你的 LoginController 上删除
String? localMemberid; //
String? localMemberid; //
String? localMemberid; //
and import main.dart
: String? localMemberid; //
并导入main.dart
:
localMemberid.value == null
? Get.toNamed(Routes.LOGIN)
: Get.toNamed(Routes.HOME);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.