简体   繁体   中英

How to Get Array Field Values From Firestore

I have a Flutter app that uses Firestore to store user data. I need help with retrieving the values stored in the 'friends' array. The image below shows the structure of my Firestore. As you can see, the 'friends' field is an array with two values: '123456' and '789123'.

Firestore 数据库的屏幕截图,显示了集合名称、文档名称以及“朋友”、“uid”和“用户名”字段。

I want to store these values in my variable called friendsList and I try to do this in getFriendsList(). To test and see if the 'friends' array values were stored in the friendsList variable, I use a print statement at the end of getFriendsList() to print the value of friendsList . But when I check my Console, Instance of 'Future<dynamic>' is printed and not the values of the 'friends' field.

How can I assign the values of the 'friends' array field from Firestore into my friendsList variable?

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:mood/components/nav_drawer.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

FirebaseAuth auth = FirebaseAuth.instance;
User currentUser;
String currentUserUID;
Future<dynamic> friendsList;

class LandingScreen extends StatefulWidget {
  static const String id = 'landing_screen';

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

class _LandingScreenState extends State<LandingScreen> {
  final _auth = FirebaseAuth.instance;

  @override
  void initState() {
    super.initState();
    getUserData();
  }

  void getUserData() {
    getCurrentUser();
    getCurrentUserUID();
    getFriendsList();
  }

  void getCurrentUser() {
    final currentUser = _auth.currentUser;
  }

  void getCurrentUserUID() {
    currentUserUID = auth.currentUser.uid;
  }

  void getFriendsList() {
    friendsList = FirebaseFirestore.instance
        .collection("Users")
        .doc(currentUserUID)
        .get()
        .then((value) {
      return value.data()["friends"];
    });
    print(friendsList);
  }

In the then callback, just assign your list to friendsList and change your friendsList to List<dynamic> type

FirebaseFirestore.instance
    .collection("Users")
    .doc(currentUserUID)
    .get()
    .then((value) {
       friendsList = value.data()["friends"];
       print(friendsList);
    });

According to your comment for async await syntax,

final value = await FirebaseFirestore.instance
    .collection("Users")
    .doc(currentUserUID)
    .get();

friendsList = value.data()["friends"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM