我在桌面 Windows 上使用 Flutter。
我想打开一个图像文件并将其加载到图像小部件中。
我收到错误消息,指出必须初始化 FileImage。
你能帮忙吗?
这是我的代码:
class MyHomePageState extends State<MyHomePage> {
late FileImage? file;
openFile () {
setState(() async {
file = await openFile();
});
}
getFilePath(){
return file.toString();
}
@override
Widget build(BuildContext context) {
Widget myfilepath = Text('Image File Path: '+getFilePath());
Widget myimage = Image.file(File(getFilePath()));
Widget openButton = SizedBox(width: 1000,height: 30,child: Row(mainAxisAlignment: MainAxisAlignment.center,mainAxisSize: MainAxisSize.min,
children: [
Expanded(child: TextButton(onPressed: openFile, child: const Text('Open File'))),
],
),
);
return Scaffold(appBar: AppBar(backgroundColor: Theme.of(context).colorScheme.inversePrimary,title: Text(widget.title),),
body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
myfilepath,
openButton,
myimage
],
),
),
);
}
}
您在 setState() 中调用了函数 openFile() ,它创建了一个递归循环, 将您的代码修改为此并在单击按钮时调用 openFile()
import 'package:file_picker/file_picker.dart';
Future<void> openFile() async {
var result = await FilePicker.platform.pickFiles(type: FileType.image);
if (result != null) {
setState(() {
file = File(result.files.single.path!);
});
}
}