如何从 firestore 中的特定文档中获取数组,并在 flutter 中使用该数据填充我的本地列表?

How to fetch arrays from a specific document in firestore and populate my local lists with that data in flutter?

你好我想做的只是填充几个列表,这些列表填充 DropdownButtonFormField() 和其他根据从下拉列表中选择的值具体列表将被发送到 SearchDelegate() class 在那里可以浏览列表,所有这些我设法让它与本地数据一起工作但现在我想更改它并将本地数据保存在 firestore 中,我做到了,但我遇到的问题是我似乎无法弄清楚如何获取这些数组并相应地填充我的列表,这是我到目前为止设法做到的。

非常感谢帮助:)

我的服务class:

class LocationsService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;

  Future<void> getLocations(){
    return _db
        .collection('locations')
        .doc('location')
        .get()
        .then((value) {
      statesList = List<String>.from(value.data['states']);
      albanianCities = List<String>.from(value.data['albanianCities']);
      ...
    });
}

我的本地列表:

List<String>? stateLists = [];
List<String>? albanianCities = [];

我遇到的错误:

The argument type 'dynamic' can't be assigned to the parameter type 'Iterable<dynamic>'.

将您的代码更改为:

statesList = List<String>.from(value.get('states') as List<dynamic> );
albanianCities = List<String>.from(value.get('albanianCities') as List<dynamic>);

因为您正试图读取文档中的一个特定字段,所以您可以使用 get("keyName") 方法。例如,您想要位于键 states 处的列表,您可以使用 get('states').

如果您想要所有字段,请使用 value.data()。注意在data()中使用(),其中returns它们作为Map<String, dyanmic>