代码之家  ›  专栏  ›  技术社区  ›  Shady Aziza

访问firebase\u auth插件版本0.2.0中的currentUser数据

  •  3
  • Shady Aziza  · 技术社区  · 8 年前

    在我的应用程序中,我有一个带有 UserAccountsDrawerHeader FirebaseAuth。例子当前用户。x

    最新 firebase_auth 0.2.0

    我已经尝试了几个小时来存储当前登录用户的信息,但尚未找到正确的方法。

    我知道我可以通过以下方式访问它们:

       Future<String> _getCurrentUserName() async {
      FirebaseUser user = await FirebaseAuth.instance.currentUser();
      return user.displayName;
    }
    

    ...

    new UserAccountsDrawerHeader(accountName: new Text(_getCurrentUserName()))
    

    使现代化

    class _MyTabsState extends State<MyTabs> with TickerProviderStateMixin {
      TabController controller;
      Pages _page;
      String _currentUserName;
      String _currentUserEmail;
      String _currentUserPhoto;
      @override
      void initState() {
        super.initState();
        _states();
        controller = new TabController(length: 5, vsync: this);
        controller.addListener(_select);
        _page = pages[0];
      }
    

    我的方法

       _states() async{
         var user = await FirebaseAuth.instance.currentUser();
         var name = user.displayName;
         var email = user.email;
         var photoUrl = user.photoUrl;
        setState(() {
          this._currentUserName=name;
          this._currentUserEmail=email;
          this._currentUserPhoto=photoUrl;
          _page = pages[controller.index];
        });
      }
    

    我的抽屉

    drawer: new Drawer(
            child: new ListView(
              children: <Widget>[
                new UserAccountsDrawerHeader(accountName: new Text(_currentUserName)  ,
                  accountEmail: new Text (_currentUserEmail),
                  currentAccountPicture: new CircleAvatar(
                   backgroundImage: new NetworkImage(_currentUserPhoto),
                  ),
    

    这是 例外 我从调试控制台获得

    I/flutter (14926): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
    I/flutter (14926): The following assertion was thrown building MyTabs(dirty, state: _MyTabsState#f49aa(tickers:
    I/flutter (14926): tracking 1 ticker)):
    I/flutter (14926): 'package:flutter/src/widgets/text.dart': Failed assertion: line 207 pos 15: 'data != null': is not
    I/flutter (14926): true.
    I/flutter (14926): Either the assertion indicates an error in the framework itself, or we should provide substantially
    

    更新2:

    这是我如何从firebase示例中修改google登录功能的:

        Future <FirebaseUser> _testSignInWithGoogle() async {
          final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
          final GoogleSignInAuthentication googleAuth =
          await googleUser.authentication;
    //checking if there is a current user
          var check = await FirebaseAuth.instance.currentUser();
          if (check!=null){
            final FirebaseUser user = check;
            return user;
          }
          else{
          final FirebaseUser user = await _auth.signInWithGoogle(
            accessToken: googleAuth.accessToken,
            idToken: googleAuth.idToken,
          );
          assert(user.email != null);
          assert(user.displayName != null);
          assert(!user.isAnonymous);
          assert(await user.getToken() != null);
    
          return user;
        }
        }
    

    我的主要功能

    void main() {
          runApp(
              new MaterialApp(
            home: new SignIn(),
            routes: <String, WidgetBuilder>{
              "/SignUp":(BuildContext context)=> new SignUp(),
              "/Login": (BuildContext context)=> new SignIn(),
              "/MyTabs": (BuildContext context)=> new MyTabs()},
    
      ));
    }
    

    onPressed: () {  _testSignInWithGoogle(). //async returns FirebaseUser
                              whenComplete(()=>Navigator.of(context).pushNamed("/MyTabs")
                              );
                            }
    

    更新1中的抽屉包含在MyTabs build中。

    2 回复  |  直到 8 年前
        1
  •  2
  •   Rémi Rousselet    8 年前

    第一:使用有状态的小部件

    class Test extends StatefulWidget {
      @override
      _TestState createState() => new _TestState();
    }
    
    class _TestState extends State<Test> {
      String _currentUserName;
    
      @override
      initState() {
        super.initState();
        doAsyncStuff();
      }
    
      doAsyncStuff() async {
        var name = await _getCurrentUserName();
        setState(() {
          this._currentUserName = name;
        });
      }
    
    
      @override
      Widget build(BuildContext context) {
        if (_currentUserName == null)
          return new Container();
        return new Text(_currentUserName);
      }
    }
    

    基本上,它是为那些不想使用有状态小部件的人准备的包装器。最后也是这样。 但你将无法在其他地方重用你的未来。

    class Test extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new FutureBuilder(
          future: _getCurrentUserName(),
          builder: (context, AsyncSnapshot<int> snapshot) {
            if (snapshot.hasData)
              return new Text(snapshot.data.toString());
            else
              return new Container();
          },
        );
      }
    }
    

    您不能直接将其与其他同步函数混合使用。 异步函数非常有用。但如果你想使用它们,只需记住两件事:

    var x = await myFuture myFuture 完成以获得结果。

    但你不能使用 await 相反,您可以使用 myFuture.then(myFunction) myFuture.whenComplete(myFunction) . myFunction 将在未来结束时调用。他们俩 .then .whenComplete 我的函数

        2
  •  1
  •   Rémi Rousselet    8 年前

    你绝对不应该这样做。你会有大量的代码重复。

    组织层(如身份验证)的最理想方式如下:

    runApp(new Configuration.fromFile("confs.json",
      child: new Authentification(
        child: new MaterialApp(
          home: new Column(
            children: <Widget>[
              new Text("Hello"),
              new AuthentifiedBuilder(
                inRoles: [UserRole.admin],
                builder: (context, user) {
                  return new Text(user.name);
                }
              ),
            ],
          ),
        ),
      ),
    ));
    

    然后,当您需要小部件中的配置或当前用户时,您可以这样做:

    @override
    Widget build(BuildContext context) {
      var user = Authentification.of(context).user;
      var host = Configuration.of(context).host;
      // do stuff with host and the user
      return new Container();
    }
    

    比如“一次编码,处处使用”。或者具有通用值并覆盖特定小部件的能力。

    这都要归功于 BuildContext context 参数这提供了一些帮助。 例如 Authentification.of(context)

    class Authentification extends StatefulWidget {
        final Widget child;
    
        static AuthentificationData of(BuildContext context) {
            final AuthentificationData auth = context.inheritFromWidgetOfExactType(AuthentificationData);
            assert(auth != null);
            return auth;
        }
    
        Authentification({this.child});
        @override
        AuthentificationState createState() => new AuthentificationState();
    }