【问题标题】:Getting this error while using imagepicker File使用 imagepicker 文件时出现此错误
【发布时间】:2022-03-04 17:19:27
【问题描述】:

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

这是我的调试控制台

这是我的聊天室源代码

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 我在这里没有任何使用地图

【问题讨论】:

  • 如果您尝试上传图片,请参考我的回答herehere 希望对您有所帮助。
  • 还是同样的错误

标签: flutter file dart imagepicker


【解决方案1】:

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

当涉及到Future's(如果你习惯了Javascript,它相当于Promise's),如果你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关键字。

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 2021-08-17
    • 2021-11-13
    • 2020-08-08
    • 2019-08-07
    • 1970-01-01
    • 2018-10-26
    • 2020-10-09
    • 1970-01-01
    相关资源
    最近更新 更多