标签: google-cloud-firestore

Flutter Cloud Firestore - 当 doc 等于当前用户 ID 时如何显示当前用户显示名称?

我有一些代码可以在创建帐户时将用户的显示名称和 uid 保存到云中。管理这个的代码在这里:

数据库.dart

Future<void> userSetup(String displayName) async {
  final CollectionReference users =
      FirebaseFirestore.instance.collection('UserNames');
  FirebaseAuth auth = FirebaseAuth.instance;
  String uid = auth.currentUser.uid.toString();
  users.doc(uid).set({'displayName': displayName, 'uid': uid});
  return;
}
Run Code Online (Sandbox Code Playgroud)

但是,我对如何检索此数据并将显示名称显示为我的个人资料页面上的文本感到困惑。这是个人资料页面的一部分:

class _HomeScreenState extends State<HomeScreen> {
  

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('KIWI'),
      ),
      drawer: MainDrawer(),
      
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SizedBox(
            height: 20.0,
          ),
          Align(
            alignment: Alignment.center,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: Colors.grey[50],
                  radius: 60.0,
                  child: Icon( …
Run Code Online (Sandbox Code Playgroud)

firebase flutter google-cloud-firestore

0
推荐指数
1
解决办法
2141
查看次数

Firebase Firestore 返回 QuerySnapshot

我刚刚开始使用 firebase 云函数和 firestore,但是当我在 firebase 云函数中使用 firestore (如下代码)时,它返回和 QuerySnapshot 而不是返回数据。如果有人以前遇到过这个问题并且已经解决了,请告诉我。这也将帮助我解决这个问题。

谢谢。

export async function allRestaurants(req: Request, res: Response) {
  try {
    // const { id } = req.params
    const restaurantsRef = admin.firestore().collection('restaurants');
    const snapshot = await restaurantsRef.get();

    console.log(">>>>>>>>>", snapshot);
    return res.status(200).send({ data: { restaurants: snapshot } })
  } catch (err) {
    return handleError(res, err)
  }
}
Run Code Online (Sandbox Code Playgroud)

javascript node.js firebase google-cloud-functions google-cloud-firestore

0
推荐指数
1
解决办法
1474
查看次数

尝试通过 Firebase Cloud 函数将 DateTime 对象发送到 Firestore

通过将 DateTime 对象从应用程序直接发送到 Firebase,会自动转换为 TimeStamp 格式。但是,如果我通过云函数发送相同的对象,我将收到以下错误:

Invalid argument: Instance of 'DateTime'
Run Code Online (Sandbox Code Playgroud)

我尝试使用该toString()方法传递对象并通过运行 Date.parse 进行后端转换Date.parse(data["birth_date"])。但在 Firestore 上,数据记录为数字而不是时间戳。

颤振代码:

//final DateTime birthDate; -> To show you the type
final HttpsCallable callable =
          CloudFunctions(region: "europe-west3").getHttpsCallable(
        functionName: 'userFunctions-editUser',
      );
      HttpsCallableResult httpsCallableResult =
          await callable.call({"birth_date": birthDate});
Run Code Online (Sandbox Code Playgroud)

服务器端代码:

exports.addUser = functions
  .region("europe-west3")
  .https.onCall((data, context) => {
    const userUid = data["userUid"];
    const docRef = admin.firestore().doc(`/users_profils/${userUid}`);

    return docRef.set({
      ...
      birth_date: Date.parse(data["birth_date"]),
      ...
    });
  });
Run Code Online (Sandbox Code Playgroud)

如何使用云函数将 DateTime 对象转换为 TimeStamp ?

firebase flutter google-cloud-functions google-cloud-firestore

0
推荐指数
1
解决办法
1160
查看次数

通过文档 ID 数组从 firebase 获取文档 (Kotlin)

有没有办法通过 ID 列表从 firebase 获取文档?我有这个列表: val IDs= listOf("id1","id2","id3","id4") 我想获取所有这些文档而不循环遍历它们。如果可能的话,像这样: Firebase.firestore.collection("users").documents(IDs).get()

android document kotlin firebase google-cloud-firestore

0
推荐指数
1
解决办法
1180
查看次数

我们可以像这样使用“Firestore”吗?

我在Github上下载了 flutter 聊天应用程序,并通过它进行学习。最初的开发人员使用了 Firestore,但在我的开发人员中,我收到错误“未定义名称‘Firestore’。请尝试将名称更正为已定义的名称,或定义名称”,如下所示。

我搜索这个并在cloudfirestore文档中阅读我们可以使用“FirebaseFirestore”(也许我错了)。我正在学习用 flutter 编写后端,到目前为止我已经完成了 UI 部分。所以这是我第一次尝试用flutter学习后端。

handleSignIn() async {
    final res = await googleSignIn.signIn();

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    final auth = await res.authentication;

    final credentials = GoogleAuthProvider.getCredential(
        idToken: auth.idToken, accessToken: auth.accessToken);

    final firebaseUser =
        (await firebaseAuth.signInWithCredential(credentials)).user;

    if (firebaseUser != null) {
      final result = (await Firestore.instance
              .collection('users')
              .where('id', isEqualTo: firebaseUser.uid)
              .getDocuments())
          .documents;

      if (result.length == 0) {
        ///new user
        Firestore.instance
            .collection('users')
            .document(firebaseUser.uid)
            .setData({
          "id": firebaseUser.uid,
          "name": firebaseUser.displayName,
          "profile_pic": firebaseUser.photoURL,
          "created_at": DateTime.now().millisecondsSinceEpoch,
        }); …
Run Code Online (Sandbox Code Playgroud)

firebase flutter google-cloud-firestore

0
推荐指数
1
解决办法
3280
查看次数

发生错误:无法读取 null 的属性“stripeId”

为了某些测试目的,我将我的 stripe 和 firebase api 密钥更改回测试模式。然而,当我尝试使用 firebase stripe api 重定向到结账时,我在控制台中遇到了这个错误:

An error occured: Cannot read property 'stripeId' of null
Run Code Online (Sandbox Code Playgroud)

但是,我的代码中没有 stripeID 存在。有趣的。这是代码。哦,请记住,这只发生在测试模式下。

var userID = "";
firebase.auth().onAuthStateChanged((user) => {
  if(user) {
    userID = user.uid
    console.log(user.uid)
}
});


export async function createCheckoutSession(activtyStatus){

  var price = 'price_1Iav0JKDPaWWeL1yBa9F7Aht'
  if (activtyStatus == "canceled") {
   
     // test price
    price = 'price_1IelOCKDPaWWeL1ynps36jkc'
  }
  


      const checkoutSessionRef =  firestore
      .collection('customers')
      .doc(userID)
      .collection('checkout_sessions')
      .add({
        price: price,
        success_url: "https://app.x.com/successPage",
        cancel_url: "https://app.x.com/signin",
    });
    
      // Wait for the CheckoutSession to get attached …
Run Code Online (Sandbox Code Playgroud)

javascript node.js stripe-payments firebase google-cloud-firestore

0
推荐指数
1
解决办法
1204
查看次数

我可以在不使用 add 方法的情况下从 flutter 生成 Doc id 到 firebase 吗?

我正在尝试使用 Uuid.v4,但是当我获取数据时,它返回为空。我发现要获取文档 id,我需要生成 id,例如:bIEUVI7MQtfWFJYU99yO 有没有办法从 flutter 生成这样的 id?

dart firebase flutter google-cloud-firestore

0
推荐指数
1
解决办法
763
查看次数

抛出错误“[core/no-app] 未创建 Firebase 应用程序 '[DEFAULT]' - 调用 Firebase.initializeApp()”

我有一个返回主页的主文件,并且在主页上我尝试调用一个新文件(test.dart)。现在的问题是这个test.dart文件抛出了一些我无法解决的错误,因为我对 flutter 和 Firebase Firestore 完全陌生。这是代码test.dart

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
// import 'package:vola1/colors.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

class test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        body: StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection('countries')
          .doc('nW9L4LGpn2MZVyiTyUII')
          .snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return Text('Loading data.. please wait..');
        return Container();
      },
    ));
  }
}


Run Code Online (Sandbox Code Playgroud)

这是它抛出的错误

======== Exception caught by widgets library =======================================================
The following FirebaseException was thrown building …
Run Code Online (Sandbox Code Playgroud)

dart firebase flutter google-cloud-firestore

0
推荐指数
1
解决办法
2万
查看次数

尝试通过 Next.js API 路由上的 admin.firestore.v1.FirestoreAdminClient 导出备份。错误:无法加载默认凭据

我正在尝试运行此代码来实现 Firestore 备份。

但这是我第一次将其部署到 Next.js 项目中。

我会在我的/api/backup终点上击中它。

const backupHandler: NextApiHandler = async (req,res) => {
  try {
  
    const admin = initializeFirebaseAdmin();
    const PROJECT_ID = getProjectId();
    
    const client = new admin.firestore.v1.FirestoreAdminClient();
    const DB_NAME = client.databasePath(PROJECT_ID, '(default)');

    const TODAY = getToday();  // YYYY-MM-DD
    const hashId = generateId().slice(0,5);
    const BUCKET = `gs://${PROJECT_ID}.appspot.com`;
    const FOLDER = `firestore-backup/${TODAY}-${hashId}`;
    const FULL_PATH = `${BUCKET}/${FOLDER}`;

    await client.exportDocuments({
      name: DB_NAME,
      outputUriPrefix: FULL_PATH,
      collectionIds: [] // CAN LIST SPECIFIC COLLECTIONS
    });

    console.log(`Backup successfully exported`);
    return res.status(200).send("Ok");
    
  }
  catch(err) …
Run Code Online (Sandbox Code Playgroud)

node.js firebase firebase-admin next.js google-cloud-firestore

0
推荐指数
1
解决办法
677
查看次数

从 Firestore 中的文档检索数组数据

这是我的 firebase 设置。

我现在面临的问题是如何使用streambuilder和listview检索文档中的数组数据item_detail并显示这样的输出

在此输入图像描述

我浏览了许多有关 Streambuilder 的网站,但找不到我想要的解决方案 可以这样做吗?

非常感谢您的惠顾。

错误

错误

dart flutter google-cloud-firestore

0
推荐指数
1
解决办法
820
查看次数