![](/img/trans.png)
[英]How to pass String type parameter in function to IconData in Flutter
[英]how to pass xFile as a function parameter in flutter
我想使用 flutter 和 HTTP package 将图像上传到服务器。 我能够显示用户选择的图像,但我想将它们上传到服务器,但是当我尝试将图像文件传递给 function 时,它给了我一个错误。
图像选择器代码:
XFile? uploadimage;
final ImagePicker _picker = ImagePicker();
Future<void> chooseImage() async {
var chooseImage = await _picker.pickImage(source: ImageSource.gallery);
setState(() {
uploadimage = chooseImage;
});
}
**服务文件代码**
AdminSupervisorServices.createNewSupervisor(
_nameController.text,
_emailController.text,
_addressController.text,
_siteController.text,
_mobileController.text,
_passwordController.text,
uploadimage // error here
)
function 本体
static createNewSupervisor(String name, String email, String address,
String site, String mobileNumber, String password, File? image) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<int> imageBytes = image!.readAsBytesSync();
String baseimage = base64Encode(imageBytes);
var token = prefs.getString("token");
var response = await http
.post(Uri.parse("$baseURL/api/mmmmmmmm"), headers: {
'Authorization': 'Bearer $token',
}, body: {
"full_name": name,
"address": address,
"mobile_no": mobileNumber,
"email": email,
"site_name": site,
"password": password,
"image": baseimage,
});
print(response.body.toString());
var data = jsonDecode(response.body);
return data;
}
...
}
try this
if this work
import 'dart:io';
/////// Import for File
final File uploadimage = File("");
final ImagePicker _picker = ImagePicker();
Future<void> chooseImage() async {
var chooseImage = await _picker.pickImage(source: ImageSource.gallery);
setState(() {
uploadimage = File(chooseImage.path);
});
}
the function you have
AdminSupervisorServices.createNewSupervisor(
_nameController.text,
_emailController.text,
_addressController.text,
_siteController.text,
_mobileController.text,
_passwordController.text,
uploadimage
);
static createNewSupervisor(String name, String email, String address,
String site, String mobileNumber, String password, File? image)async{
...
}
编辑:
如果您将图像传递给 json 那么您错过的是data:image/png;base64类似这样的东西让我们假设这个 function 返回字符串。
///include import path
import 'package:path/path.dart' as path;
///////////////////////////////////////
imagetobase64(String? imagePath){
final extension = path.extension(imagePath
.substring(imagePath.lastIndexOf("/"))
.replaceAll("/", ""));
//// the extension return is png or jpg or jpeg which is needed
final bytes = File(imagePath).readAsBytesSync();
String base64 =
"data:image/${extension.replaceAll(".", "")};base64,${base64Encode(bytes)}";
return base64;
}
uploadimage 是 XFile 类型的吗? 并且您将其传递给接受文件参数的 function? 类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.