如何从外部存储器获取图像并使用Flutter播放

xzv2uavs  于 2023-03-09  发布在  Flutter
关注(0)|答案(1)|浏览(171)
Container(
    child: Image.file(File("/source/emulated/0/Nathanael/solo/01.jpg")),
)

当我尝试从外部存储打开我的图像时发生错误,当然我有所需的权限。
我遇到的错误是:

════════ Exception caught by image resource service ════════════════════════════
The following PathNotFoundException was thrown resolving an image codec:
Cannot retrieve length of file, path = '/source/emulated/0/Nathanael/solo/01.jpg' (OS Error: No such file or directory, errno = 2)

嗨,亲爱的,我是一个初学者在flutter编程,我试图从我的外部存储打开一个图像,当然知道完整的路径,但当我试图用image.file()打开它,它接受参数的文件,我不能这样做,我不知道我这样做是否正确的方式,请帮助我...

x7rlezfr

x7rlezfr1#

图像.文件

若要从目标设备的文件系统加载图像,必须使用Image.file。但是,必须首先确保应用具有访问设备外部存储的适当权限。打开并编辑项目的AndroidManifest.xml文件以请求这些权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package= "flutter.image.demo">
        <uses-permission android:name = 
            "android.permission.READ_EXTERNAL_STORAGE"/>
    <application
    ...
    </application>
</manifest>

有了文件路径,可以将图像添加到程序代码中:

Image.file(new File('/source/emulated/0/Nathanael/solo/01.jpg'))

请注意,您还必须导入'dart:io'库才能使用File类。

import 'package:flutter/material.dart';
import 'dart:io';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Image Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Image Demo'),
        ),
        body: new Container(
          color: Colors.grey[200],
          child: Image.file(
             new File('/source/emulated/0/Nathanael/solo/01.jpg')),
          alignment: Alignment.center,
        ),
      ),
    );
  }
}

如果上述解决方案不起作用,请检查以下权限处理程序permission handlder & example链接

**另一种方法:**处理权限要访问存储中的文件,应用需要具有读取存储的权限。否则,用户将收到权限错误,除非文件位于应用的目录中。处理权限的最简单方法是使用第三方程序包,如permission_handler。首先,在pubspec.yaml的依赖项部分添加程序包

permission_handler: ^5.1.0+2

运行flutter pub get(或在Android Studio中单击“Packages get”)后,可以通过添加此import语句来使用软件包。

import 'package:permission_handler/permission_handler.dart';

示例实施:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Woolha.com Flutter Tutorial',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Woolha.com | ImageFile Example'),
          backgroundColor: Colors.teal,
        ),
        body: FileImageExample(),
      ),
    );
  }
}

class FileImageExample extends StatefulWidget {

  @override
  _FileImageExampleState createState() => _FileImageExampleState();
}

class _FileImageExampleState extends State<FileImageExample> {

  PermissionStatus _permissionStatus;

  initState() {
    super.initState();

        () async {
      _permissionStatus = await Permission.storage.status;

      if (_permissionStatus != PermissionStatus.granted) {
        PermissionStatus permissionStatus= await Permission.storage.request();
        setState(() {
          _permissionStatus = permissionStatus;
        });
      }
    } ();
  }

  @override
  Widget build(BuildContext context) {
    if (_permissionStatus != PermissionStatus.granted) {
      return Text('Not granted');
    }

    return Image.file(
      File('/storage/emulated/0/Download/test.jpg'),
      width: 100,
      height: 100,
      fit: BoxFit.fill,
      repeat: ImageRepeat.repeat,
      alignment: Alignment.topCenter,
      color: Colors.red,
      colorBlendMode: BlendMode.saturation,
      //      scale: 4,
      errorBuilder: (
          BuildContext context,
          Object error,
          StackTrace stackTrace,
          ) {
        print(error);
        print(stackTrace);
        return Container(
          color: Colors.grey,
          width: 100,
          height: 100,
          child: const Center(
            child: const Text('Error load image', textAlign: TextAlign.center),
          ),
        );
      },
      frameBuilder: (
          BuildContext context,
          Widget child,
          int frame,
          bool wasSynchronouslyLoaded,
          ) {
        return Container(
          decoration: BoxDecoration(
            border: Border.all(color: Colors.red, width: 5),
          ),
          child: child,
        );
      },
    );
    //    return Image(
    //      image: FileImage(
    //        File('/storage/emulated/0/Download/test.jpg'),
    //        scale: 4
    //      ),
    //    );
  }
}

相关问题