简体   繁体   English

如何将用户名存储在包含 email 和同一用户发送的聊天消息的同一文档中? 在 flutter 和 firebase

[英]How do I store the username in the same document that contains the email and chat messages sent by the same user? in flutter and firebase

I want to store the username in the same document that will contain a message from this user so that I can display the message with the username, but I could not get the username from the new account registration page, I could only get the sender's email and add it to the document for each message.我想将用户名存储在包含来自该用户的消息的同一文档中,以便我可以显示带有用户名的消息,但我无法从新帐户注册页面获取用户名,我只能获取发件人的 email并将其添加到每条消息的文档中。

New user registration page:新用户注册页面:

 

  const RegistrationScreen({Key? key}) : super(key: key);

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

class _RegistrationScreenState extends State<RegistrationScreen> {
  final _auth = FirebaseAuth.instance;

  late String email;
  late String password;
  late String username;

  bool showSpinner = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextField(
            onChanged: (value) {
              username = value;
            },
            decoration: InputDecoration(
              hintText: 'username',
            ),
          ),
          TextField(
            onChanged: (value) {
              email = value;
            },
            decoration: InputDecoration(
              hintText: 'email',
            ),
          ),
          TextField(
            onChanged: (value) {
              password = value;
            },
            decoration: InputDecoration(
              hintText: 'password',
            ),
          ),
          ElevatedButton(
            child: Text('register'),
            onPressed: () async {
              try {
                final newUser = await _auth.createUserWithEmailAndPassword(
                    email: email, password: password);
                Navigator.pushNamed(context, ChatScreen.screenRoute);
                setState(() {
                  showSpinner = false;
                });
              } catch (e) {
                print(e);
              }
            },
          )
        ],
      ),
    );
  }
}

The chat page: on this page I get the sender's email and his message in a document, then I display it again in the application, and now I also want to get the username to display it with the message.聊天页面:在这个页面上我得到发件人的 email 和他在文档中的消息,然后我在应用程序中再次显示它,现在我还想获得用户名来显示它与消息。

final _firestore = FirebaseFirestore.instance;
late User signedInUser;

class ChatScreen extends StatefulWidget {


  const ChatScreen({Key? key}) : super(key: key);

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

class _ChatScreenState extends State<ChatScreen> {
  final messageTextController = TextEditingController();
  final _auth = FirebaseAuth.instance;

  String? messageText;
  @override
  void initState() {
    super.initState();
    getCurrentUser();
  }

  void getCurrentUser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        signedInUser = user;
        print(signedInUser.email);
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          messageStreamBuilder(),
          Container(
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: messageTextController,
                    onChanged: (value) {
                      messageText = value;
                    },
                    decoration: InputDecoration(
                      hintText: 'Write your message here...',
                    ),
                  ),
                ),
                TextButton(
                  onPressed: () {
                    messageTextController.clear();
                    _firestore.collection('messages').add({
                      'text': messageText,
                      'sender': signedInUser.email,
                     
                    });
                  },
                  child: Text(
                    'send',
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class messageStreamBuilder extends StatelessWidget {
  const messageStreamBuilder({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
        stream: _firestore.collection('messages').snapshots(),
        builder: (context, snapshot) {
          List<messageLine> messageWidgets = [];
          if (!snapshot.hasData) {
            return CircularProgressIndicator(
              backgroundColor: Colors.blue,
            );
          }
          final messages = snapshot.data!.docs;
          for (var message in messages) {
            final messageText = message.get('text');
            final messageSender = message.get('sender');

            final currentUser = signedInUser.email;

            final messageWidget = messageLine(
              sender: messageSender,
              text: messageText,
            );
            messageWidgets.add(messageWidget);
          }
          return Expanded(
            child: ListView(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
              children: messageWidgets,
            ),
          );
        });
  }
}

class messageLine extends StatelessWidget {
  const messageLine({this.text, this.sender, Key? key}) : super(key: key);

  final String? sender;
  final String? text;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '$sender',
          
          ),
          Material(
            child: Text(
              '$text',
            
            ),
          ),
        ],
      ),
    );
  }
}

in this function, You can use like this to achive that在这个 function 中,你可以这样使用来实现

 void getCurrentUser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        String user_Name = user.displayName;
        String image_Url = user.photoUrl;
        String email_Id = user.email;
        String user_Uuid = user.uid; // etc
        print(user_Name );
      }
    } catch (e) {
      print(e);
    }
  }

after that pass the user_name to firebase之后将用户名传递给 firebase

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过 flutter 中的文档从 firebase 存储中检索数据? - How do i retrieve data from firebase store by document in flutter? 如何同时为移动和桌面制作 Flutter Firebase 应用程序 - How to do a Flutter Firebase app for both Mobile and Desktop at the same time 链接多个用户帐户(同一电子邮件) Firebase - Link several user accounts (same email) Firebase 如何在Firebase中注册email包含大写字母的用户认证 - How to register a user whose email contains a capital letter in Firebase Authentication 如何在 Vue ref 中存储 Firebase 9 onAuthStateChanged 用户 object? - How do I store a Firebase 9 onAuthStateChanged user object in a Vue ref? 如何从 flutter firebase base 中的单个文档读取一次数据(不是实时的)? - How do I read data from a single document in flutter firebase base once (not in real time)? 如何防止同一用户与 Firebase 同时登录? - How to prevent simultaneous logins of the same user with Firebase? Flutter Firebase 即使发送和输入的 OTP 相同,OTP 验证仍失败 - Flutter Firebase OTP verification fails even though both sent and entered OTP are the same 我可以使用 twilio 验证在 SMS 和 Email 中发送相同的 OTP 吗? - Can I sent the same OTP in SMS and in Email using twilio verify? 如何在 firebase 上保存相同 JS 代码的多个实例? - How do I save multiple instances of the same JS code on firebase?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM