AssetImage和Image.asset有什么区别 - Flutter

54
在我的应用程序中,我使用这两个类,但我不知道哪一个应该优先考虑。
Image.asset('icons/heart.png')
AssetImage('icons/hear.png')

也许有人能更快地获取图像。

2个回答

92

Image是一个StatefulWidget,而Image.asset仅仅是一个命名构造函数,你可以直接在你的小部件树上使用它。

AssetImage是一个ImageProvider,负责获取指定路径的图像。

如果您查看Image.asset的源代码,您会发现它正在使用AssetImage来获取图像。

  Image.asset(String name, {
      Key key,
      AssetBundle bundle,
      this.semanticLabel,
      this.excludeFromSemantics = false,
      double scale,
      this.width,
      this.height,
      this.color,
      this.colorBlendMode,
      this.fit,
      this.alignment = Alignment.center,
      this.repeat = ImageRepeat.noRepeat,
      this.centerSlice,
      this.matchTextDirection = false,
      this.gaplessPlayback = false,
      String package,
      this.filterQuality = FilterQuality.low,
    }) : image = scale != null
           ? ExactAssetImage(name, bundle: bundle, scale: scale, package: package)
           : AssetImage(name, bundle: bundle, package: package),
         assert(alignment != null),
         assert(repeat != null),
         assert(matchTextDirection != null),
         super(key: key); 

6

感谢 @diegoveloper From flutter version 2.5, 推荐使用const修饰符的Image StatefulWidget,但是在Image.asset中不可能实现这一点。然而,你需要将image path作为参数提供给AssetImage对象,并将此对象作为Image StatefulWidget的' image '的命名参数的值,如下所示。

  Image(
        image: AssetImage('asset/dice1.png'),
       )

从推荐的Dart教程书《Dart学徒》中可以了解到,constfinal修饰符对于对象能够减少后续的编译时间和运行时间。 因此,在编写简洁、少量代码时,请使用Image.asset;而在需要快速且CPU友好的代码时,请使用Image StatefulWidget


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接