简体   繁体   English

为什么 flutter 在类内部为 Firestore 方法返回错误,但在小部件内部很好?

[英]Why does flutter return an error for Firestore methods inside of classes but is fine inside of widget?

So I tried creating a model classes similar to rails, laravel or other frameworks so that I could organize my code better and I wanted to add instance methods to save data to firebase here is my class.所以我尝试创建一个类似于 rails、laravel 或其他框架的模型类,以便我可以更好地组织我的代码,我想添加实例方法以将数据保存到 firebase,这是我的类。 However, for some reason when I call the save method on my event class.但是,出于某种原因,当我在我的事件类上调用 save 方法时。 I get this error MissingPluginException(No implementation found for method DocumentReference#setData on channel plugins.flutter.io/cloud_firestore).我收到此错误 MissingPluginException(在频道 plugins.flutter.io/cloud_firestore 上找不到方法 DocumentReference#setData 的实现)。

I tried running flutter clean, after googling, upgrading flutter, uninstalling the app, and running packages get and nothing worked.我尝试运行 flutter clean,在谷歌搜索、升级 flutter、卸载应用程序和运行包之后,没有任何效果。 Finally I tried just creating normal function inside of my widget component to create a new document and add data.最后,我尝试在我的小部件组件中创建普通函数来创建一个新文档并添加数据。 The function worked fine without an error.该功能运行良好,没有错误。 Also, yes, I did the appropriate imports of importing cloud firestore into my event class as well geoflutterfire.另外,是的,我做了适当的导入,将 cloud firestore 导入我的事件类以及 geoflutterfire。 Why am I getting the error and is there a way to organize my code?为什么我会收到错误消息,有没有办法组织我的代码? Do firestore methods not work in dart files that aren't widgets that inherit from stateless widget or statfefull widget? firestore 方法在不是从无状态小部件或 statfefull 小部件继承的小部件的 dart 文件中不起作用吗? I tried importing foundation and material dart packages and they were both greyed out with Firestore and my privateEvent class obviously not using it.我尝试导入基础和材料飞镖包,它们都被 Firestore 变灰,我的 privateEvent 类显然没有使用它。

  final bool feedbackLocationOrActivity;
  final String id;
  final bool feedbackTimeAndDate;
  final String name;
  final String mediaUrl;
  final String address;
  final DateTime startTime;
  final DateTime endTime;
  List categories;
  final String creatorId;
  final String groupId;
  final GeoFirePoint location;
  List coHosts;
  final String details;
  final bool guestsCanInviteFriends;

  PrivateEvent(
      {this.feedbackLocationOrActivity,
      this.id,
      this.feedbackTimeAndDate,
      this.name,
      this.mediaUrl,
      this.address,
      this.startTime,
      this.endTime,
      this.categories,
      this.creatorId,
      this.location,
      this.coHosts,
      this.guestsCanInviteFriends,
      this.details,
      this.groupId});

  factory PrivateEvent.fromDocument(DocumentSnapshot doc) {
    return PrivateEvent(
        id: doc['id'],
        feedbackLocationOrActivity: doc['feedbackLocationOrActivity'],
        feedbackTimeAndDate: doc['feedbackTimeAndDate'],
        name: doc['name'],
        mediaUrl: doc['mediaUrl'],
        address: doc['address'],
        startTime: doc['startTime'],
        endTime: doc['endTime'],
        categories: doc['categories'],
        creatorId: doc['creatorId'],
        groupId: doc['groupId'],
        coHosts: doc['coHosts'],
        guestsCanInviteFriends: doc['guestsCanInviteFriends'],
        details: doc['details'],
        location: doc['location']);
  }

  save() async {
    return Firestore.instance
        .collection('privateEvents')
        .document(this.groupId)
        .collection("events")
        .add({
      "id": this.id,
      "feedbackLocationOrActivity": this.feedbackLocationOrActivity,
      "feedbackTimeAndDate": this.feedbackTimeAndDate,
      "name": this.name,
      "mediaUrl": this.mediaUrl,
      "address": this.address,
      "startTime": this.startTime,
      "endTime": this.endTime,
      "categories": FieldValue.arrayUnion(this.categories),
      "creatorId": this.creatorId,
      "location": this.location.data,
      "details": this.details,
      "coHosts": FieldValue.arrayUnion(this.coHosts),
      "guestsCanInviteFriends": this.guestsCanInviteFriends
    }).then((response) {
      response.updateData({"id": response.documentID});
      return true;
    }).catchError((onError) {
      print("this is the error $onError");
      return false;
    });
  }
}

The save method is the method that should save it to the database however it gets an error.

Here is where I call it.

createEvent({screenWidth, screenHeight, isLandscape}) async {
    setState(() {
      loading = true;
    });
    final String mediaUrl = await uploadImage(file);
    if (mediaUrl.isEmpty || mediaUrl == null) {
      setState(() {
        loading = false;
      });
      eventTimeWarning(
          screenWidth: screenWidth,
          screenHeight: screenHeight,
          isLandscape: isLandscape,
          warningMessage:
              "Your image didn't upload properly. There could be a problem with your internet connection. Please try again");
      return;
    }
    PrivateEvent privateEvent = PrivateEvent(
        feedbackTimeAndDate: feedbackTimeAndDate,
        feedbackLocationOrActivity: feedbackLocationOrActivity,
        name: eventName,
        mediaUrl: mediaUrl,
        address: eventAddress,
        startTime: eventStartTimeAndDate,
        endTime: eventEndTimeAndDate,
        categories: selectedCategories(),
        creatorId: Provider.of<UserData>(context).getUserId,
        location: eventLocation,
        guestsCanInviteFriends: guestsCanInviteFriends,
        details: detailsController.text.trim(),
        groupId:
            Provider.of<PrivateGroupNormalData>(context).getGroupId); 

    final bool eventUploadSuccess = await sendEventInfo();
    if (!eventUploadSuccess) {
      setState(() {
        eventTimeWarning(
            screenWidth: screenWidth,
            screenHeight: screenHeight,
            isLandscape: isLandscape,
            warningMessage:
                "There was a problem creating your event. Please, check your internet connection and try again.");
        loading = false;
      });
      return;
    }
    print("EVENT CREATED SUCCESSFULLY!");
  }

As I said before. The above doesn't work. However On creating a function within the widget. The data is added to the database and there is no missingexception error.

Here is the working version.

Future<bool> sendEventInfo({String mediaUrl}) {
    return Firestore.instance
        .collection('privateEvents')
        .document(Provider.of<PrivateGroupNormalData>(context).getGroupId)
        .collection("events")
        .add({
      "feedbackLocationOrActivity": this.feedbackLocationOrActivity,
      "feedbackTimeAndDate": this.feedbackTimeAndDate,
      "name": this.eventName,
      "mediaUrl": mediaUrl,
      "address": eventAddress,
      "startTime": eventStartTimeAndDate,
      "endTime": eventEndTimeAndDate,
      "categories": selectedCategories(),
      "creatorId": Provider.of<UserData>(context).getUserId,
      "location": eventLocation.data,
      "details": detailsController.text.trim(),
      "coHosts": FieldValue.arrayUnion(),
      "guestsCanInviteFriends": this.guestsCanInviteFriends
    }).then((response) {
      response.updateData({"id": response.documentID});
      return true;
    }).catchError((onError) {
      print("this is the error $onError");
      return false;
    });
  } 

All I do is replace the call to instance method with the call to the above function and now it works fine without the missing plugin error.

答案是我必须使我的 Firestore 实例成为静态实例才能正确访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 firestore 查询不返回 Flutter/dart 移动应用程序内的文档,但适用于 javascript - firestore query does not return documents inside flutter/dart mobile app, but works in javascript Flutter Firestore 更新集合内的文档名称 - Flutter Firestore update document name inside of collection 在 Flutter 中的嵌套集合中查询 Firestore 文档 - Query Firestore documents inside a nested collection in Flutter 如何使用 Flutter 在 Firestore 中的文档内创建集合? - How to create a collection inside a document in Firestore with Flutter? 为什么 Firestore 有时不返回任何东西,没有错误,什么都没有? - Why does Firestore sometimes not return anything, no error, nothing? 更新 Firestore 中数组的 Map 数据 - Flutter - Update the Map data of an Array inside Firestore - Flutter Flutter:Firestore 在 StreamBuilder 中获取用户 uid - Flutter: Firestore Get User uid inside StreamBuilder Flutter 错误:无法访问从 Firebase Firestore 获取的快照内的数据 - Flutter error : Failure to access data inside a snapshot fetched from Firebase Firestore 颤振:扩展小部件内的 ListView 在我的颤动应用程序中没有滚动 - flutter: ListView inside Expanded widget is not scrolling in my flutter app 为什么我在 QuerySnapShot firestore flutter 上遇到错误? - Why im getting error on QuerySnapShot firestore flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM