如何初始化FileImage

问题描述 投票:0回答:1

我在桌面 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
          ],
        ),
      ),

    );
  }
}
flutter
1个回答
0
投票

您在 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!); 
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.