使用 imagepicker 文件时出现此错误

发布于 2025-01-11 18:07:24 字数 6816 浏览 0 评论 0原文

我正在尝试从设备中选取图像并将其存储在 firebase 上并在聊天屏幕中显示。但是,每当我使用此文件时,它都会显示以下错误。上次我使用 File 时没有出现位置参数错误。是因为新的更新吗?

这是我的调试控制台

在此处输入图像描述

这是我的聊天室源代码

import 'dart:html';
import 'dart:typed_data';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ChatRoom extends StatefulWidget {
  final Map<String, dynamic> userMap;
  final String chatRoomId;
  ChatRoom({required this.chatRoomId, required this.userMap});

  @override
  State<ChatRoom> createState() => _ChatRoomState();
}

class _ChatRoomState extends State<ChatRoom> {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  final TextEditingController _massage = TextEditingController();
  File? imageFile;
   

 
  Future getImage() async {
    ImagePicker _picker = ImagePicker();

    await _picker.pickImage(source: ImageSource.gallery).then((xFile) {
      if (xFile != null) {
        imageFile = File(xFile.path);

      }
    });
  }

  onSendMassage() async {
    if (_massage.text.isNotEmpty) {
      Map<String, dynamic> massages = {
        "sendby": _auth.currentUser!.displayName,
        "massage": _massage.text,
        "time": FieldValue.serverTimestamp(),
        "type": "text"
      };

      await _firestore
          .collection("chatroom")
          .doc(widget.chatRoomId)
          .collection("chat")
          .add(massages);
      _massage.clear();
    } else {
      _firestore
          .collection('chatroom')
          .doc(widget.chatRoomId)
          .collection('chats')
          .orderBy("time", descending: false)
          .snapshots();
      print("please input some massage");
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        leading: new Container(
          child: new IconButton(
            icon: new Icon(Icons.arrow_back_ios),
            onPressed: () {/* Your code */},
          ),
        ),
        title: Text('username'),
        backgroundColor: Colors.grey[850],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 16,
            ),
            Container(
              height: size.height / 1.25,
              width: size.width,
              child: StreamBuilder<QuerySnapshot>(
                stream: _firestore
                    .collection('chatroom')
                    .doc(widget.chatRoomId)
                    .collection('chat')
                    .orderBy("time", descending: false)
                    .snapshots(),
                builder: (BuildContext context, snapshot) {
                  if (snapshot.data != null) {
                    return ListView.builder(
                      itemCount: snapshot.data!.docs.length,
                      itemBuilder: (context, index) {
                        Map<String, dynamic> map = snapshot.data!.docs[index]
                            .data() as Map<String, dynamic>;
                        return messages(size, map, context);
                      },
                    );
                  } else {
                    return Container(
                      child: Center(
                        child: Text('data'),
                      ),
                    );
                  }
                },
              ),
            ),
            Container(
              height: size.height / 10,
              width: size.width,
              alignment: Alignment.center,
              child: Container(
                height: size.height / 12,
                width: size.width / 1.1,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    PhysicalModel(
                      color: Colors.white,
                      elevation: 42,
                      shadowColor: Color.fromARGB(255, 64, 64, 65),
                      borderRadius: BorderRadius.circular(20),
                      child: Container(
                        height: size.height / 16,
                        width: size.width / 1.3,
                        child: TextField(
                          controller: _massage,
                          decoration: InputDecoration(
                            contentPadding: const EdgeInsets.all(12),
                            border: InputBorder.none,
                            suffixIcon: IconButton(
                              onPressed: () {},
                              icon: Icon(Icons.photo),
                            ),
                            hintText: "Send Message",
                          ),
                        ),
                      ),
                    ),
                    IconButton(
                        icon: Icon(
                          Icons.arrow_circle_right_rounded,
                          size: 38,
                        ),
                        onPressed: onSendMassage),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Widget messages(Size size, Map<String, dynamic> map, BuildContext context) {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  return map['type'] == "text"
      ? Container(
          width: size.width,
          alignment: map['sendby'] == _auth.currentUser!.displayName
              ? Alignment.centerRight
              : Alignment.centerLeft,
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 14),
            margin: EdgeInsets.symmetric(vertical: 5, horizontal: 8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15),
              color: Colors.blue,
            ),
            child: Text(
              map['massage'] ?? "",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
          ),
        )
      : Container(
          height: size.height / 2.5,
          width: size.width,
          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
          alignment: map['sendby'] == _auth.currentUser!.displayName
              ? Alignment.centerRight
              : Alignment.centerLeft,
        );
}

ID,现在要在地图 arg 中给出 我在这里没有使用地图

I'm trying to pick an image from device and store it on firebase and display it in chat screen. But, whenever I'm using this file its showing following error. Last time when I used File there was no posational arg errors . Is it due to new update?

Here's my debug console

enter image description here

here's my chatroom source code

import 'dart:html';
import 'dart:typed_data';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ChatRoom extends StatefulWidget {
  final Map<String, dynamic> userMap;
  final String chatRoomId;
  ChatRoom({required this.chatRoomId, required this.userMap});

  @override
  State<ChatRoom> createState() => _ChatRoomState();
}

class _ChatRoomState extends State<ChatRoom> {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  final TextEditingController _massage = TextEditingController();
  File? imageFile;
   

 
  Future getImage() async {
    ImagePicker _picker = ImagePicker();

    await _picker.pickImage(source: ImageSource.gallery).then((xFile) {
      if (xFile != null) {
        imageFile = File(xFile.path);

      }
    });
  }

  onSendMassage() async {
    if (_massage.text.isNotEmpty) {
      Map<String, dynamic> massages = {
        "sendby": _auth.currentUser!.displayName,
        "massage": _massage.text,
        "time": FieldValue.serverTimestamp(),
        "type": "text"
      };

      await _firestore
          .collection("chatroom")
          .doc(widget.chatRoomId)
          .collection("chat")
          .add(massages);
      _massage.clear();
    } else {
      _firestore
          .collection('chatroom')
          .doc(widget.chatRoomId)
          .collection('chats')
          .orderBy("time", descending: false)
          .snapshots();
      print("please input some massage");
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        leading: new Container(
          child: new IconButton(
            icon: new Icon(Icons.arrow_back_ios),
            onPressed: () {/* Your code */},
          ),
        ),
        title: Text('username'),
        backgroundColor: Colors.grey[850],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 16,
            ),
            Container(
              height: size.height / 1.25,
              width: size.width,
              child: StreamBuilder<QuerySnapshot>(
                stream: _firestore
                    .collection('chatroom')
                    .doc(widget.chatRoomId)
                    .collection('chat')
                    .orderBy("time", descending: false)
                    .snapshots(),
                builder: (BuildContext context, snapshot) {
                  if (snapshot.data != null) {
                    return ListView.builder(
                      itemCount: snapshot.data!.docs.length,
                      itemBuilder: (context, index) {
                        Map<String, dynamic> map = snapshot.data!.docs[index]
                            .data() as Map<String, dynamic>;
                        return messages(size, map, context);
                      },
                    );
                  } else {
                    return Container(
                      child: Center(
                        child: Text('data'),
                      ),
                    );
                  }
                },
              ),
            ),
            Container(
              height: size.height / 10,
              width: size.width,
              alignment: Alignment.center,
              child: Container(
                height: size.height / 12,
                width: size.width / 1.1,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    PhysicalModel(
                      color: Colors.white,
                      elevation: 42,
                      shadowColor: Color.fromARGB(255, 64, 64, 65),
                      borderRadius: BorderRadius.circular(20),
                      child: Container(
                        height: size.height / 16,
                        width: size.width / 1.3,
                        child: TextField(
                          controller: _massage,
                          decoration: InputDecoration(
                            contentPadding: const EdgeInsets.all(12),
                            border: InputBorder.none,
                            suffixIcon: IconButton(
                              onPressed: () {},
                              icon: Icon(Icons.photo),
                            ),
                            hintText: "Send Message",
                          ),
                        ),
                      ),
                    ),
                    IconButton(
                        icon: Icon(
                          Icons.arrow_circle_right_rounded,
                          size: 38,
                        ),
                        onPressed: onSendMassage),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Widget messages(Size size, Map<String, dynamic> map, BuildContext context) {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  return map['type'] == "text"
      ? Container(
          width: size.width,
          alignment: map['sendby'] == _auth.currentUser!.displayName
              ? Alignment.centerRight
              : Alignment.centerLeft,
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 14),
            margin: EdgeInsets.symmetric(vertical: 5, horizontal: 8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15),
              color: Colors.blue,
            ),
            child: Text(
              map['massage'] ?? "",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
          ),
        )
      : Container(
          height: size.height / 2.5,
          width: size.width,
          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
          alignment: map['sendby'] == _auth.currentUser!.displayName
              ? Alignment.centerRight
              : Alignment.centerLeft,
        );
}

id now to give in map arg I don't have any use of map here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尤怨 2025-01-18 18:07:24

首先,您将 Future.thenasync/await 语法结合起来,在这种情况下这是不正确的。

当谈到 Future 时(如果你习惯了 Javascript,这相当于 Promise),如果你 await 它们,无需使用 then 方法。

在这种情况下,您应该这样做:

Future getImage() async {
  ImagePicker _picker = ImagePicker();

  // Use final if you won't reassing the variable
  final XFile file = await _picker.pickImage(source: ImageSource.gallery);
  if (file != null && file.path != null) {
    imageFile = File(file.path);
  }
}

我们正在等待结果,然后将其分配给变量。或者,如果您想使用 Future.then 语法,该方法应该是:

Future getImage() {
  ImagePicker _picker = ImagePicker();

  // Use final if you won't reassing the variable
  _picker.pickImage(source: ImageSource.gallery).then((file) { 
    if (file != null && file.path != null) {
      imageFile = File(file.path);
    }
  })
}

请参阅方法签名不包含 async 关键字。

First of all, you are combining the Future.then, with the async/await syntax, which, is not correct in this case.

When it comes to Future's (which are the equivalent of Promise's if you are used to Javascript), if you await them, there's no need to use the then method.

In this case, you should do:

Future getImage() async {
  ImagePicker _picker = ImagePicker();

  // Use final if you won't reassing the variable
  final XFile file = await _picker.pickImage(source: ImageSource.gallery);
  if (file != null && file.path != null) {
    imageFile = File(file.path);
  }
}

We are awaiting the result and then assigning it to the variable. Alternatively, if you want to use the Future.then syntax, the method should be:

Future getImage() {
  ImagePicker _picker = ImagePicker();

  // Use final if you won't reassing the variable
  _picker.pickImage(source: ImageSource.gallery).then((file) { 
    if (file != null && file.path != null) {
      imageFile = File(file.path);
    }
  })
}

See as the method signature does not include the async keyword.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文