基本问题:需要在整个flutter应用程序中访问Class。
要求:不要让它成为我访问的有状态窗口小部件。
只希望我可以通过在其他页面上导入来访问一个类。我坚持使用一组变量的用户登录名,并且我不想不必将此对象逐页推送。
想简单地访问类值
我无法使用单例或其他解决方案找到任何很好的例子,这给了我我想要的东西。
import 'package:myApp/models/user.dart';
MyClass.Username = "testUser"; //Set the username
String currentUser = MyClass.Username; // Get the username
//Here is the top of the User class - is this creating a class that will
//only be defined once in the app, so if I set a value it will persist ?
class User {
static User _user = new User._internal();
factory User() {
return _user;
}
User._internal();
//More stuff
....}
答案 0 :(得分:0)
如果要创建单例类以在应用程序的任何位置访问同一实例,则源代码将显示一个单例类的示例。阅读评论。
class UserRepository {
static UserRepository _instance = new UserRepository._internal();
static get instance => _instance; // this is a get method that return _instance private class field
// the name member is accessible directly like a public field
String name;
UserRepository._internal( ){
name = " singleton name property";
}
// this is a instance method
void myInstanceMethod(){
print("hello my singleton");
}
} //end of your singleton class
// usage in any point of your app.
UserRepository.instance.myInstanceMethod();
var myInstance = UserRepository.instance; // getting instance singleton reference
//accessing name class member
print("The name is: ${myInstance.name}";)
myInstance.name = "user name";
print("Now the name is: ${myInstance.name}" );
//or you can access like this way too
UserRepository.instance.name = " User name";
print("The name is: ${UserRepository.instance.name}" );