首页 > 解决方案 > currentUser.displayName 不起作用并在短时间内返回 null

问题描述

使用时出现错误:

FirebaseAuth.instance.currentUser.updateProfile(displayName: username)

当我登录并导航到使用currentuser.displayname的屏幕时,它工作正常,但随后它会显示一两秒钟的错误,然后自行更新。此后,显示名称按预期工作。

似乎有一个滞后,但我不确定如何删除它。我现在一直在为此苦苦挣扎。我非常感谢社区的任何建议。

我在哪里更新userprofile并将用户名添加到displayname

class AuthScreen extends StatefulWidget {
    @override
    _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State {
    final _auth = FirebaseAuth.instance;
    var _isLoading = false;
    String name;
    void _submitAuthForm(
    String username,
    String email,
    String password,
    String phoneNum,
    bool isLogin,
    
    BuildContext ctx,) async {
     UserCredential authResult;

try {
  setState(() {
    _isLoading = true;
  });
  if (isLogin) {
    authResult = await _auth.signInWithEmailAndPassword(
      email: email,
      password: password,
    );
  } else {
    authResult = await _auth.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );

    print("username is: " + username);

    _auth.currentUser.updateProfile(displayName: username);

    await FirebaseFirestore.instance
        .collection('users')
        .doc(authResult.user.uid)
        .set({
      'phoneNum': phoneNum,
      'name': username,
      'email': email,
    });
  }
} on PlatformException catch (err) {
  var message = 'An error occurred, pelase check your credentials!';

  if (err.message != null) {
    message = err.message;
  }

  ScaffoldMessenger.of(ctx).showSnackBar(
    SnackBar(
      content: Text(message),
      backgroundColor: Theme.of(ctx).errorColor,
    ),
  );
  setState(() {
    _isLoading = false;
  });
} catch (err) {
  print(err);
  setState(() {
    _isLoading = false;
  });
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).primaryColor,
body: AuthForm(
_submitAuthForm,
_isLoading,
),
);
}
}

我在哪里使用显示名称

class HeyAman extends StatelessWidget {
    final user = FirebaseAuth.instance.currentUser;
    @override
    Widget build(BuildContext context) {
        List firstname = user.displayName.split(' ');
        return StreamBuilder(stream: FirebaseAuth.instance.userChanges(), builder: (ctx, futureSnapshot) {
    if (futureSnapshot.connectionState == ConnectionState.none) {
      return Center(
        child: CircularProgressIndicator(),
      );
    }
    return Container(
      padding: const EdgeInsets.only(bottom: 7, left: 30, right: 30),
      child: Column(
        children: <Widget>[
          Container(
            width: 300,
            child: Text(
              user.displayName.indexOf(' ') > -1
                  ? firstname[0]
                  : user.displayName,
              style: TextStyle(
                fontWeight: FontWeight.w800,
                color: Colors.white,
                fontSize: 33,
              ),
            ),
          ),
        ],
      ),
    );
  },
);
}
}

调试控制台,它会暂时显示错误:

    Reloaded 2 of 650 libraries in 1,344ms. D/FirebaseAuth( 7789): Notifying id token listeners 
    about a sign-out event. D/FirebaseAuth( 7789): Notifying auth state listeners about a sign-out 
    event. W/IInputConnectionWrapper( 7789): getSelectedText on inactive InputConnection 
    W/IInputConnectionWrapper( 7789): getTextAfterCursor on inactive InputConnection 
    W/IInputConnectionWrapper( 7789): beginBatchEdit on inactive InputConnection 
    W/IInputConnectionWrapper( 7789): endBatchEdit on inactive InputConnection 
    W/IInputConnectionWrapper( 7789): getTextBeforeCursor on inactive InputConnection 
    W/IInputConnectionWrapper( 7789): getSelectedText on inactive InputConnection 
    W/IInputConnectionWrapper( 7789): getTextAfterCursor on inactive InputConnection I/FirebaseAuth( 
    7789): [FirebaseAuth:] Preparing to create service connection to fallback implementation W/System 
    ( 7789): Ignoring header X-Firebase-Locale because its value was null.

标签: firebasefluttergoogle-cloud-firestorefirebase-authentication

解决方案


推荐阅读