dart - 如何使用 image.file 加载图像

我似乎无法简单地将图像从硬盘加载到屏幕上。 Image.network 看起来很简单。但我不知道如何使用 Image 或 Image.file。图像似乎需要一个流,所以我认为这不是我想要的。

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

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

class MyApp extends StatelessWidget {
    File file = new File("Someimage.jpeg");
    @override
    Widget build(BuildContext context) {
        return new MaterialApp(
            home: new Image.file(file),  //doesn't work, but no errors
        );
    }
}

我将 Someimage 添加到 pubspec.yaml 文件中,但这也不起作用:

assets:
    - Someimage.jpeg

谁能给我一个例子来说明这是如何做到的?谢谢。

最佳答案

Image之间的区别和关系, ImageProvider :

Image :

Creates a widget that displays an image.

To show an image from the network or an asset bundle, consider using [new Image.network] and [new Image.asset] respectively.

所以 Image是一个小部件。点赞<img> html中的标签。

ImageProvider :

Identifies an image without committing to the precise final asset. This allows a set of images to be identified and for the precise image to later be resolved based on the environment, e.g. the device pixel ratio.

所以 ImageProvider就像 src Image 的属性.

现在 Image接受一个参数 image这是一个 ImageProvider . 有 4 种方式获取 ImageProvider

  • AssetImage :

    用于加载与 apk 一起打包的预定义图像集。

    例如要显示横幅图像,需要一些自定义图标。

  • NetworkImage :

    用于从互联网加载动态图片。

  • FileImage :

    用于从目标设备中的文件系统加载图像。

    例如显示新下载的图像。

  • MemoryImage :

    用于从内存中加载原始图像。

    例如获取用户的壁纸并将其加载到小部件中。

现在他们都是ImageProviders . 其中任何一个都可以用作image Image 的属性小部件。 Flutter 社区通过在 Image 中添加扩展类来简化语法。小部件本身。

所以

  • Image.asset(name)本质上是 Image(image: AssetImage(name)) ,
  • Image.file(path)本质上是 Image(image: FileImage(File(path))) ,
  • Image.network(url)本质上是 Image(image: NetworkImage(url)) ,
  • Image.memory(list)本质上是 Image(image: MemoryImage(list))

现在应该很清楚了

  • apk 大小随着 Assets 图片的数量而增加。

  • 他们的加载时间(用户看到的)通常是按顺序排列的

    NetworkImage > FileImage > AssetImage > MemoryImage

https://stackoverflow.com/questions/49835623/

相关文章:

listview - Flutter:SimpleDialog 中的 ListView

flutter - 在 Flutter 中选择时更改 ListTile 的背景颜色

http - 如何将查询参数添加到 Dart http 请求中?

regex - 如何在 Dart 中使用正则表达式?

android - 如何在 Flutter App 中处理 onPause/onResume?

dart - 如何格式化定位文本 block 的背景颜色?

dart - Flutter 中的文本字段验证

dart - Flutter - 容器中的顶部对齐文本

dart - 如何在 Flutter 中播放自定义声音?

android - Flutter/Dart 静态变量丢失/不断重新初始化