颤振:如何从http请求创建单例

颤振:如何从http请求创建单例,http,dart,flutter,Http,Dart,Flutter,我想声明一个用户对象,我将用http请求实例化它,我希望它是全局的。我怎么做?和一个单身汉?但是我怎样才能使这个班也成为单身学生呢?还是有别的办法? 这就是我到目前为止所做的: class User{ String username; String password; int id; User({this.username, this.id}); factory User.fromJson(Map<String, dynamic> json){ return Us

我想声明一个用户对象,我将用http请求实例化它,我希望它是全局的。我怎么做?和一个单身汉?但是我怎样才能使这个班也成为单身学生呢?还是有别的办法? 这就是我到目前为止所做的:

class User{
String username;
String password;
  int id;

User({this.username, this.id});

  factory User.fromJson(Map<String, dynamic> json){
    return User(
      username: json['name'],
      id: json['id']
    );
  }

}

在弗利特,你不应该做单身汉。相反,您应该将其存储到一个小部件中,该小部件向其所有子体公开这些数据。 通常
InheritedWidget

原因是,有了这样的体系结构,所有的后代都会自动意识到对“singleton”所做的任何更改

典型的例子如下:

@immutable
class User {
  final String name;

  User({this.name});
}

class Authentificator extends StatefulWidget {
  static User currentUser(BuildContext context) {
    final _AuthentificatorScope scope = context.inheritFromWidgetOfExactType(_AuthentificatorScope);
    return scope.user;
  }

  final Widget child;

  Authentificator({this.child, Key key}): super(key: key);

  @override
  _AuthentificatorState createState() => _AuthentificatorState();
}

class _AuthentificatorState extends State<Authentificator> {
  @override
  Widget build(BuildContext context) {
    return _AuthentificatorScope(
      child: widget.child,
    );
  }
}

class _AuthentificatorScope extends InheritedWidget {
  final User user;

  _AuthentificatorScope({this.user, Widget child, Key key}) : super(child: child, key: key);

  @override
  bool updateShouldNotify(_AuthentificatorScope oldWidget) {
    return user != oldWidget.user;
  }
}
然后在页面内部使用如下内容:

new MaterialApp(
  title: 'Flutter Demo',
  builder: (context, child) {
    return Authentificator(
      child: child,
    );
  },
  home: Home(),
);
@override
Widget build(BuildContext context) {
  User user = Authentificator.currentUser(context);
  ...
}

你真的不想在你的应用程序中出现单身。我认为您真正想要的是访问在小部件树顶部附近共享的
用户
对象的方法。你可以用类似的东西。通过这种方式,您可以将
User
对象定义为一个模型,包括执行登录的方法,将
ScopedModel
包装在根目录周围,并在有登录按钮或用户名文本标签的地方使用
scopedModelSecondant
。这可能是一个愚蠢的问题,但如果我使用Navigator.of(context)。pushnamedRemoveUntil,ScopedModeleScendant是否找到用户对象?
Navigator.of
将向上搜索小部件层次结构,直到找到最近的NavigatorState。如果您只使用WidgetsApp或MaterialApp提供导航,那么它将找到这个小部件。这意味着,只要你用
ScopedModel
包装你的应用程序,那么即使你改变了路径,作用域模型的后代也能找到它。非常感谢!这可能是个愚蠢的问题,但如果我使用Navigator.of(context).pushname和removeUntil,它是否也会起同样的作用?不确定这是什么意思,例如,在范围模型中,它会覆盖小部件树。我不知道remove是否会删除这些关系。也许不是,但只是问一下:导航器堆栈和小部件树都没有更新。非常感谢!
@override
Widget build(BuildContext context) {
  User user = Authentificator.currentUser(context);
  ...
}