添加到AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
使用正确的文件路径
有时,选择器返回的路径在平板电脑上可能会有所不同。确保您正确处理文件路径。
确保文件正确保存
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:typed_data';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class VideoPicker extends StatefulWidget {
@override
_VideoPickerState createState() => _VideoPickerState();
}
class _VideoPickerState extends State<VideoPicker> {
final ImagePicker _picker = ImagePicker();
Future<void> pickVideo() async {
try {
final XFile? result = await _picker.pickVideo(source: ImageSource.camera);
if (result != null) {
Uint8List dataList = await result.readAsBytes();
print("File length: ${dataList.length}");
// Get the temporary directory
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
// Create a file to save the video
File videoFile = File('$tempPath/${result.name}');
// Write the video bytes to the file
await videoFile.writeAsBytes(dataList);
print("Video saved at: ${videoFile.path}");
} else {
print("No video selected");
}
} catch (e) {
print("Error picking video: $e");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Video Picker"),
),
body: Center(
child: ElevatedButton(
onPressed: pickVideo,
child: Text("Pick Video from Camera"),
),
),
);
}
}
void main() => runApp(MaterialApp(
home: VideoPicker(),
));