进行验证会议进行检查的最佳场所仍然活着



我正在构建一个使用本机(iOS和Android(框架进行身份验证的应用程序。我创建了一个插件,该插件将所有框架暴露的方法都包裹起来飘动。我必须检查用户经过身份验证并且会话还活着的每个屏幕更改,如果不调用框架,则在flutter中最好的位置是什么?

在小部件内部。小部件几乎总是要放置逻辑的地方。

准确地说,您想要的是一种使用自定义static MyInheritedWidget of(BuildContext context)方法来揭示继承的widget的状态空间。将具有所有登录信息和一些" on Change"方法。

然后,您将能够使用MyAuth.of(context)访问应用程序内部的 ,因此可以访问所有所需的数据。

通常您会以此为例:

/// The user data model. May be serializable. Usually immutable
@immutable
class MyUser {
  const MyUser({this.name});
  final String name;
}
/// The entry point of your global logic.
/// Most of the time, will only take one child as parameter
/// and nothing else. And will also expose a [of] method
class MyAuth extends StatefulWidget {
  final Widget child;
  const MyAuth({this.child});
  /// Fetch the closest [_MyInheritedAuth] from the widget tree
  /// using context. And bind the widget possessing that context
  /// to reload evytimes the inherited widget changes
  static _MyInheritedAuth of(BuildContext context) {
    final _MyInheritedAuth inherited = context.inheritFromWidgetOfExactType(_MyInheritedAuth);
    return inherited;
  }
  @override
  _MyAuthState createState() => new _MyAuthState();
}
typedef void MyUserNameChange(String name);
/// Your controller. Will handle all the logic and just
/// pass it all to [_MyInheritedAuth]
class _MyAuthState extends State<MyAuth> {
  MyUser user;
  @override
  initState() {
    super.initState();
    user = const MyUser(name: 'foo');
  }
  void onUserNameChange(String name) {
    setState(() {
      user = new MyUser(name: name);
    });
  }
  @override
  Widget build(BuildContext context) {
    return new _MyInheritedAuth(user: user, editUserName: onUserNameChange, child: widget.child,);
  }
}
/// What the other widgets will get when user [MyAuth.of].
/// Inherit from [InheritedWidget] to be able to bind a context
/// to this widget's updates/
class _MyInheritedAuth extends InheritedWidget {
  final MyUser user;
  final MyUserNameChange editUserName;
  const _MyInheritedAuth({ @required this.user, @required this.editUserName, @required Widget child,}): super(child: child);
  @override
  bool updateShouldNotify(_MyInheritedAuth oldWidget) {
    return user != oldWidget.user || editUserName != oldWidget.editUserName;
  }
}

,只要您需要使用用户Infos,就可以做MyAuth.of(context).user

最新更新