firebase 无此方法和jsonDocumentReference错误

4si2a6ki  于 2023-02-13  发布在  其他
关注(0)|答案(1)|浏览(128)

我有一个项目,我想在其中更新用户到firebase数据库的状态,还想更新获取存储的状态。我编写了一个代码,它给了我两个错误

1. this error Happens when I upload the document to the firebase database it works fine and i can see the changes in database but somehow giving these exception it says :

E/flutter ( 2958): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_JsonDocumentReference'
E/flutter ( 2958): #0      _JsonStringifier.writeObject (dart:convert/json.dart:794:7)
E/flutter ( 2958): #1      _JsonStringifier.writeMap (dart:convert/json.dart:875:7)
E/flutter ( 2958): #2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:830:21)
E/flutter ( 2958): #3      _JsonStringifier.writeObject (dart:convert/json.dart:785:9)
E/flutter ( 2958): #4      _JsonStringStringifier.printOn (dart:convert/json.dart:983:17)
E/flutter ( 2958): #5      _JsonStringStringifier.stringify (dart:convert/json.dart:968:5)
E/flutter ( 2958): #6      JsonEncoder.convert (dart:convert/json.dart:345:30)
E/flutter ( 2958): #7      JsonCodec.encode (dart:convert/json.dart:231:45)
E/flutter ( 2958): #8      StorageImpl.flush (package:get_storage/src/storage/io.dart:34:37)
E/flutter ( 2958): #9      GetStorage._flush (package:get_storage/src/storage_impl.dart:144:23)
E/flutter ( 2958): #10     GetQueue._check (package:get/get_utils/src/queue/get_queue.dart:42:47)
E/flutter ( 2958): #11     GetQueue.add (package:get/get_utils/src/queue/get_queue.dart:29:5)
E/flutter ( 2958): #12     GetStorage._addToQueue (package:get_storage/src/storage_impl.dart:139:18)
E/flutter ( 2958): #13     Microtask.exec.<anonymous closure> (package:get_storage/src/storage_impl.dart:174:17)
E/flutter ( 2958): #14     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 2958): #15     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter ( 2958): 
W/le.helping_han( 2958): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed)
[GETX] GOING TO ROUTE /Profile

下面是我第二个错误:2.第二个我无法理解的错误,在我上传文档到Firebase和我去配置文件后,我得到这个错误:热重新加载后,错误消失

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Profile(dirty):
Class '_JsonDocumentReference' has no instance method '[]'.
Receiver: Instance of '_JsonDocumentReference'
Tried calling: []("status")

The relevant error-causing widget was: 
  Profile Profile:file:///D:/FIVERR%20PROJECTS%20FLUTTER/helping_hand/helping_hand/lib/drawers/Slidedrawer.dart:22:20
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1      Profile.build (package:helping_hand/UI/Other/Profile.dart:65:120)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:4949:49)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#5      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
#6      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
...     Normal element mounting (275 frames)

下面是我代码:
条控制器. dart(使用GetxController)

// status
  Future<void> addStatus(Map<String,String> userStatus) async {
    loadingbar();
    try{
      final DocumentReference userstatus= FirebaseFirestore.instance
          .collection('users')
          .doc(Auth().currentuser?.email);
      await userstatus.update({
        "status":userStatus['status'],"description":userStatus['description'],
      });
      Userbox.write('userStatus', userstatus);
    }catch(e){
      if (kDebugMode) {
        print('add status error ::: $e');
      }
        Get.snackbar('error','we have encountered an error');
    }

    loadingbaroff();
  }

  bool isloading = false;

  void loadingbar() {
    isloading = true;
    update();
  }
  void loadingbaroff() {
    isloading = false;
    update();
  }

鱼,注射:

Container(
                    width: MediaQuery.of(context).size.width-50,
                    margin: const EdgeInsets.only(top: 16,bottom: 24,left: 8,right: 8),
                    child: ElevatedButton(
                        style: const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent) ),
                        onPressed: () async {
                          if(selectpartycontroller.text.isNotEmpty&&description.text.isNotEmpty){
                            Map<String,String> userstatus = ({"status":selectpartycontroller.text.toString(), "description":description.text.toString(),});
                            await barController.addStatus(userstatus);
                            selectpartycontroller.clear();
                            description.clear();
                            if (kDebugMode) {
                              print(Userbox.read(Userbox.read('userdata')['country_code']));
                            }
                          }else{
                            Get.snackbar('fill details', 'select an option and add a description');
                          }
                        },
                        child:const Text('Continue',style: TextStyle(color: Colors.white),))),

轮廓省道:

Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(top: 24,bottom: 12,left: 24,right: 12),
              child: Text('User status : ${Userbox.read('userStatus') == null? 'not fetched':Userbox.read('userStatus')['status']}',
                style: const TextStyle(color: Colors.redAccent,fontWeight: FontWeight.normal,fontSize: 16),),),
            Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(top: 24,bottom: 12,left: 24,right: 12),
              child: Text('status description : ${Userbox.read('userStatus')== null?'not fetched':Userbox.read('userStatus')['description']}',
                style: const TextStyle(color: Colors.redAccent,fontWeight: FontWeight.normal,fontSize: 16),),),
xj3cbfub

xj3cbfub1#

对于第一个错误,请检查出现问题的目录并查看如何修复。

Profile Profile:file:///D:/FIVERR%20PROJECTS%20FLUTTER/helping_hand/helping_hand/lib/drawers/Slidedrawer.dart:22:20

出现第二个错误的原因是键“status”为null,因此要处理这个问题,请添加null检查,

// status
    Future<void> addStatus(Map<String, String> userStatus) async {
      loadingbar();
      try {
        final DocumentReference userstatus = FirebaseFirestore.instance
            .collection('users')
            .doc(Auth().currentuser?.email);
        await userstatus.update({
          if (userStatus['status'] != null) "status": userStatus['status'],
          if (userStatus['description'] != null)
            "description": userStatus['description'],
        });
        Userbox.write('userStatus', userstatus);
      } catch (e) {
        if (kDebugMode) {
          print('add status error ::: $e');
        }
        Get.snackbar('error', 'we have encountered an error');
      }

      loadingbaroff();
    }

    bool isloading = false;

    void loadingbar() {
      isloading = true;
      update();
    }

    void loadingbaroff() {
      isloading = false;
      update();
    }

在userstatus中,您需要删除“toString()”方法并在整个操作之后清除Controllers

Container(
                    width: MediaQuery.of(context).size.width-50,
                    margin: const EdgeInsets.only(top: 16,bottom: 24,left: 8,right: 8),
                    child: ElevatedButton(
                        style: const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent) ),
                        onPressed: () async {
                          if(selectpartycontroller.text.isNotEmpty&&description.text.isNotEmpty){
                            Map<String,String> userstatus = ({"status":selectpartycontroller, "description":description.text,});
                            await barController.addStatus(userstatus);
                            
                            if (kDebugMode) {
                              print(Userbox.read(Userbox.read('userdata')['country_code']));
                            }
                          }else{
                            Get.snackbar('fill details', 'select an option and add a description');
                          }
                        selectpartycontroller.clear();
                            description.clear();},
                        child:const Text('Continue',style: TextStyle(color: Colors.white),))),

相关问题