在 Flutter 中创建一个空数组并将其发送到带有空值的 Firestore?

Create an empty array and send it to Firestore with an empty value in Flutter?

我想在发布 Feed 时在 Firestore 中创建一个空数组。但是该数组在 Firestore 中显示为 null。这是我的代码。请帮忙。

   class FeedModel {
    
      final String imgUrl;
      final String desc;
      final String authorName;
      final String profileImg;
      final String title;
      final int likeCount;
      List<String> strArr = [];   // this the array i want to create it in firestore
    
      FeedModel({this.imgUrl, this.desc,this.authorName,this.profileImg,this.title,this.likeCount, this.strArr});
    
      Map<String, dynamic> toMap(){
        return {
         "imgUrl" : this.imgUrl,
          "desc" : this.desc,
          "authorName" : this.authorName,
          "profileImg" : this.profileImg,
          "like_count" : this.likeCount,
          "liked_user_id" : this.strArr
        };
      }
   
    }

发送数据代码如下:

Future<void> _sendData() async {

    try {
      final StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child('myimage.jpg');
      final StorageUploadTask task = firebaseStorageRef.putFile(_image);
      StorageTaskSnapshot taskSnapshot = await task.onComplete;
      String downloadUrl = await taskSnapshot.ref.getDownloadURL();
      final String pname = myController.text;
      final  String pimgurl = downloadUrl;
      final String pauthorName = "Sachin Tendulkar";
      final String pprofileImg = "https://i.picsum.photos/id/564/200/200.jpg?hmac=uExb18W9rplmCwAJ9SS5NVsLaurpaCTCBuHZdhsW25I";
      final String ptitle = "Demo Data";
      final int plikeCount= 0;
      List<String> pLikeduserId;  // This line returning null as show in image
      print(pimgurl);
      final FeedModel feeds = FeedModel(imgUrl: pimgurl ,desc: pname,authorName: pauthorName ,profileImg: pprofileImg,title: ptitle,likeCount: plikeCount, strArr : pLikeduserId );
      insertData(feeds.toMap());

    }  catch (e) {
      print(e);
    }

  }

空图片:

想要像下图那样:

如何在创建提要时像上一张图​​片一样发送数组?

没有太多理由将其存储为值为 '' 的数组。相反,最好在使用以下内容从 firebase 接收值时进行空检查:liked_userid = /*insert method of getting firebase user ID*/??[]

这样,当您使用 liked_userid 时,它不会为空,而是一个空列表。

如果你真的想要一个内部值为 '' 的列表,而不是更改 toMap 函数的内部:

Map<String, dynamic> toMap(){
    return {
     "imgUrl" : this.imgUrl,
      "desc" : this.desc,
      "authorName" : this.authorName,
      "profileImg" : this.profileImg,
      "like_count" : this.likeCount,
      "liked_user_id" : this.strArr=[]?['']:this.strArr//line that was changed
    };
  }

这将使您拥有一个内部带有 [''] 的数组,但我仍然会推荐我展示的第一种方法。

如果您想要在字段中使用一个数组,即使是一个空数组,您也必须为其分配一个实际的列表值。现在,通过根本不分配任何实际的列表值,您实际上是在为 liked_user_id.

分配一个空值

所以,给它一个值:

List<String> pLikeduserId = [];

这将写入一个空列表字段。

执行此操作以创建一个包含空字符串的数组。

Map<String, dynamic> toMap() {
    return {
        'liked_user_id': List.generate(1, (r) => "")
    };
}

等待_fireStore.collection("COLLECTION_NAME").document("DOUCUMENT_NAME").setData({ "KEY_VALUE": [], });

这会在 Cloud FireStore 中创建一个空数组。