flutter //未处理的异常:对空值使用了空检查运算符//

jhkqcmku  于 2023-02-13  发布在  Flutter
关注(0)|答案(2)|浏览(166)

当我点击堆栈小工具中的相机图标时,它也无法更新图像,它显示此错误。它也不会将图像上传到数据库,也不会更改URL**[错误:flutter/runtime/dart_vm_initializer.cc(41)]未经处理的异常:空值E/flutter上使用的空检查运算符(28471):#0 _个人资料状态.geturl(套餐:电子商务/身份认证/个人资料.日期:25:59)E/flutter(28471):**我想更新图像,但遇到错误,请解决它..
图像打印机代码

Future image(BuildContext context) async{
  showModalBottomSheet(
    elevation: 5,
    enableDrag: true,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
    ),
    context: context,
    builder: (BuildContext context) {
      return Container(
        height: 200,
        child: Column(
          children: [
            ///Gallery
            ListTile(
              leading: Icon(Icons.browse_gallery),
              title: Text("Pick image from gallery"),
              onTap: () async{
                final gallery=await ImagePicker().pickImage(source: ImageSource.gallery);
if (gallery!=null) {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text("Image Picked successfull",style: TextStyle(color: Colors.redAccent),
    ),duration: Duration(seconds: 5),
  ));
} else {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text("Please pick image for further proccess",style: TextStyle(color: Colors.redAccent),
    ),duration: Duration(seconds: 5),
  ));
}

用于更新URL的代码

Future geturl(context)async{
  final id=DateTime.now().toString();
  final reference=FirebaseFirestore.instance.collection("user3");
await image(context);
  final storage.Reference ref =
  storage.FirebaseStorage.instance.ref('/images'+id);
  final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
  await Future.value(uploadTask);
  final  downurl=await ref.getDownloadURL();
  print(FirebaseAuth.instance.currentUser!.uid);
  reference.doc(FirebaseAuth.instance.currentUser!.uid).update(
      {
        "imageurl":downurl.toString(),
      }
  ).then((value) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text("Updated successfully",style: TextStyle(color: Colors.redAccent),
      ),duration: Duration(seconds: 5),
    ));
  }).catchError((e){
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text("${e.message}",style: TextStyle(color: Colors.redAccent),
      ),duration: Duration(seconds: 5),
    ));
  });
}

用于在扑动应用程序中显示图像

Stack(

                          alignment: Alignment.bottomRight,
                          children: [
                            CircleAvatar(
                              radius: 70,
                              backgroundImage:_image!=null?FileImage(_image!.absolute) : NetworkImage(snapshot.data!.docs[index]["imageurl"]) as ImageProvider,
                            ),
                             InkWell(
                                 onTap: (){
geturl(context);
                                 },
                                 child: Icon(Icons.add_a_photo,size: 30,)),
                          ],
                        ),

请解决我最近几天遇到的此错误

g6ll5ycj

g6ll5ycj1#

我认为这条线是问题的根源:

final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);

因为_image可能是空的,你在哪里给变量_image赋值呢?

    • 编辑:**

我将如何解决这个问题:
你有一个方法pickImage,它显示底部模态表并允许用户拾取图像。如果用户拾取图像,你调用一个方法将拾取的图像保存到firebase,在本例中调用该方法:保存图像

void pickImage(BuildContext context) {
    showModalBottomSheet(
      elevation: 5,
      enableDrag: true,
      isDismissible: false,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 200,
          child: Column(
            children: [
              ListTile(
                leading: Icon(Icons.browse_gallery),
                title: Text("Pick image from gallery"),
                onTap: () async {
                  XFile? pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery);
                  if (pickedImage != null) {
                    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                      content: Text(
                        "Image Picked successfull",
                        style: TextStyle(color: Colors.redAccent),
                      ),
                      duration: Duration(seconds: 5),
                    ));
                    var image = Image.memory(await pickedImage.readAsBytes());
                    // save image to firebase
                    saveImage(context, image);
                  } else {
                    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                      content: Text(
                        "Please pick image for further proccess",
                        style: TextStyle(color: Colors.redAccent),
                      ),
                      duration: Duration(seconds: 5),
                    ));
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

将映像保存到firebase的方法:

Future saveImage(context, _image) async {
    final id = DateTime.now().toString();
    final reference=FirebaseFirestore.instance.collection("user3");
    final storage.Reference ref =
    storage.FirebaseStorage.instance.ref('/images'+id);
    final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
    await Future.value(uploadTask);
    final  downurl=await ref.getDownloadURL();
    print(FirebaseAuth.instance.currentUser!.uid);
    reference.doc(FirebaseAuth.instance.currentUser!.uid).update(
        {
          "imageurl":downurl.toString(),
        }
    ).then((value) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text("Updated successfully",style: TextStyle(color: Colors.redAccent),
        ),duration: Duration(seconds: 5),
      ));
    }).catchError((e){
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text("${e.message}",style: TextStyle(color: Colors.redAccent),
        ),duration: Duration(seconds: 5),
      ));
    });
  }
cs7cruho

cs7cruho2#

您需要通过添加“?"声明图像变量null。
示例:数据类型图像?
然后像这样显示

image!=null ? CircleAvatar(
                          radius: 70,
                          backgroundImage: FileImage(_image!.absolute) ,
                        ): CircleAvatar(
                          radius: 70,
                          backgroundImage: NetworkImage(snapshot.data!.docs[index]["imageurl"])

相关问题