【问题标题】:flutter firebase [connect UserID to Profile collection]flutter firebase [将用户 ID 连接到配置文件集合]
【发布时间】:2021-07-09 01:12:24
【问题描述】:

我正在学习颤振,但我遇到了一个问题。 我创建了一个小应用程序,允许我在 firebase 上通过 Gmail 进行身份验证。 一旦我登录电子邮件,生成的名称就会添加到“集合:用户”中

现在我想在“collection: profilepage”中添加更多关于用户的信息。

在我的 main.dart 上我问:用户是否已登录,然后 返回(用户名选择器)。

在 UserNameChooser 中,我有 2 个文本字段,它们将被写入“collection: profilepage”。

现在我的问题:如何从“集合:用户”中获取用户 ID 并添加 “collection: profilepage”的 ID。

或者您如何管理个人资料页面身份验证连接?

我尝试了很多方法,但都无法完成......

我的 Main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:signal/services/auth.dart';
// import 'package:signal/views/home.dart';
import 'package:signal/views/usernamechooser.dart';
import 'views/signin.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
     
        primarySwatch: Colors.lightBlue,
      ),
      home: FutureBuilder(
        future: AuthMethods().getCurrentUser(),
        builder: (context, AsyncSnapshot<dynamic> snapshot) {
          if(snapshot.hasData){
            return UserNameChooser();
          }
          else{
            return SignIn();
          }
        }
      ),
    );
  }
}

我的 auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:signal/helperfunctions/sharedpref_helper.dart';
import 'package:signal/services/database.dart';
import 'package:signal/views/home.dart';

class AuthMethods{
  final FirebaseAuth auth = FirebaseAuth.instance;

  getCurrentUser() async {
    return await auth.currentUser;
  }

  signInWithGoogle(BuildContext context) async {
    final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
    final GoogleSignIn _googleSignIn = GoogleSignIn();

    final GoogleSignInAccount googleSignInAccount = 
      await _googleSignIn.signIn();

    final GoogleSignInAuthentication googleSignInAuthentication = await
    googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.credential(
      idToken: googleSignInAuthentication.idToken,
      accessToken: googleSignInAuthentication.accessToken
      );

      UserCredential result = 
        await _firebaseAuth.signInWithCredential(credential);
  
      User userDetails = result.user;

      if(result != null){
        SharedPreferenceHelper().saveUserEmail(userDetails.email);
        SharedPreferenceHelper().saveUserId(userDetails.uid);
        SharedPreferenceHelper()
            .saveUserName(userDetails.email.replaceAll("@gmail.com", ""));
        SharedPreferenceHelper().saveDisplayName(userDetails.displayName);
        SharedPreferenceHelper().saveUserProfileUrl(userDetails.photoURL);
        
        Map<String, dynamic> userInfoMap = {
          "email": userDetails.email,
          "username": userDetails.email.replaceAll("@gmail.com", ""),
          "name": userDetails.displayName,
          "imgUrl": userDetails.photoURL
        };
        
        DatabaseMethods()
        .addUserInfoToDB(userDetails.uid, userInfoMap)
        .then((value) {
            Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (context) => Home()));
          });
    }
  }
  Future signOut() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.clear();
    await auth.signOut();
  }
}

我的数据库.dart

import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:signal/helperfunctions/sharedpref_helper.dart';

class DatabaseMethods{
  Future addUserInfoToDB(String userId, Map<String, dynamic>userInfoMap)
async {
    return FirebaseFirestore.instance
    .collection("users")
    .doc(userId)
    .set(userInfoMap);
  }

  Future<Stream<QuerySnapshot>> getUserByUserName(String username) async{
    return FirebaseFirestore.instance
    .collection("users")
    .where("username", isEqualTo: username)
    .snapshots();
  }



Future addMessage(String chatRoomId, String messageId, Map messageInfoMap) async {
  return FirebaseFirestore.instance
  .collection ("chatrooms")
  .doc(chatRoomId)
  .collection("chats")
  .doc(messageId)
  .set(messageInfoMap);
  }

  updateLastMessageSend(String chatRoomId, Map lastMessageInfoMap){
    return FirebaseFirestore.instance
    .collection("chatrooms")
    .doc(chatRoomId)
    .update(lastMessageInfoMap);
  }
  
  createChatRoom(String chatRoomId, Map chatRoomInfoMap) async{
    final snapShot = await FirebaseFirestore.instance
    .collection("chatrooms")
    .doc(chatRoomId)
    .get();

    if(snapShot.exists){
      //chatroom already exists
      return true;
    }else{
      //chatroom does not exists
      return FirebaseFirestore.instance
      .collection("chatrooms")
      .doc(chatRoomId)
      .set(chatRoomInfoMap);
    }
  }

  Future<Stream<QuerySnapshot>> getChatRoomMessages(chatRoomId) async {
    return FirebaseFirestore.instance
        .collection("chatrooms")
        .doc(chatRoomId)
        .collection("chats")
        .orderBy("ts", descending: true)
        .snapshots();
  }

  Future<Stream<QuerySnapshot>> getChatRooms() async {
    String myUsername = await SharedPreferenceHelper().getUserName();
    return FirebaseFirestore.instance
      .collection("chatrooms")
      .orderBy("lastMessageSendTs", descending: true)
      .where("users",arrayContains: myUsername)
      .snapshots();
    }

  Future<QuerySnapshot> getUserInfo(String username) async {
    return await FirebaseFirestore.instance
      .collection("users")
      .where("username", isEqualTo: username)
      .get();
  }
}

我的用户名chooser.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:signal/views/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:signal/helperfunctions/sharedpref_helper.dart';








Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    MaterialApp(home: UserNameChooser(),));
}
class UserNameChooser extends StatefulWidget{
    @override
  _UserNameChooserState createState() => _UserNameChooserState();
}
class _UserNameChooserState extends State<UserNameChooser> {
  String userNameKey, getUserId;

  TextEditingController chosenusername = new TextEditingController();
  TextEditingController chosenage = new TextEditingController();
    
    
    Future<String> getUserName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(userNameKey);
  }
 

  @override
  Widget build(BuildContext context){
    return Scaffold(
      
      appBar: AppBar(title: Text("usernamechooser"),
      ),
      body: Container(
        
        padding: EdgeInsets.all(40.0),
        child: Center(child: Column(
          children: [
            Container(
              
            ),
            TextFormField(
              controller: chosenusername,
              decoration: InputDecoration(
                hintText: "Username"
              ),
            ),
          SizedBox(
            height: 10.0,
          ),
          TextFormField(
            controller: chosenage,
            decoration: InputDecoration(
              hintText: "alter"
            ),
          ),
          SizedBox(
            height: 10.0,
            
          ),
 


 
          TextButton(
            onPressed: (){
              Map <String,dynamic> data = {"choseusername": chosenusername.text,"chosenage": chosenage.text};
              FirebaseFirestore.instance.collection("userprofile").add(data);
               
               
               Navigator.push(context, MaterialPageRoute(builder: (context) => Home(),));

               },
              child: Text("Submit"),

          ), 
            
        ] 
      
      ),
    )
    
  )
  
  );

}
}

最后但并非最不重要的是我的 shared_preferences.dart



import 'package:shared_preferences/shared_preferences.dart';


class SharedPreferenceHelper {
  static String userIdKey = "USERKEY";
  static String userNameKey = "USERNAMEKEY";
  static String displayNameKey = "USERDISPLAYNAMEKEY";
  static String userEmailKey = "USEREMAILKEY";
  static String userProfilePicKey = "USERPROFILEPICKEY";

  //save data
  Future<bool> saveUserName(String getUserName) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(userNameKey, getUserName);
  }

  Future<bool> saveUserEmail(String getUseremail) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(userEmailKey, getUseremail);
  }

  Future<bool> saveUserId(String getUserId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(userIdKey, getUserId);
  }

  Future<bool> saveDisplayName(String getDisplayName) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(displayNameKey, getDisplayName);
  }

  Future<bool> saveUserProfileUrl(String getUserProfile) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(userProfilePicKey, getUserProfile);
  }

  // get data
  Future<String> getUserName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(userNameKey);
  }

  Future<String> getUserEmail() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(userEmailKey);
  }

  Future<String> getUserId() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(userIdKey);
  }

  Future<String> getDisplayName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(displayNameKey);
  }

  Future<String> getUserProfileUrl() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(userProfilePicKey);
  }
}

【问题讨论】:

  • 您好,我有点怀疑为什么您需要从 firestore 获取 UserID,当您可以通过获取当前用户的 id 将当前用户的 id 放入 profilepage 集合时auth.currentUser.uid的授权用户ID
  • 问题在于,在所有博客文章和 stackoverflow 上,它都类似于:firebase.auth.currentUser.uid .. 但这对我不起作用......仅适用于:FirebaseAuth.instance.currentUser.uid ;

标签: firebase flutter google-cloud-firestore firebase-authentication flutter-dependencies


【解决方案1】:

问题已解决...

我是怎么做到的:

我将 currentUser.uid 加载到 var useruid ..

var useruid = FirebaseAuth.instance.currentUser.uid;

并将这个 uid 发送给用户 db :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2020-10-13
    相关资源
    最近更新 更多