【问题标题】:What is the difference between AssetImage and Image.asset - FlutterAssetImage 和 Image.asset 有什么区别 - Flutter
【发布时间】:2018-11-14 22:22:52
【问题描述】:

在我的应用程序中,我使用了这 2 个类,但我不知道应该优先考虑哪一个。

Image.asset('icons/heart.png')
AssetImage('icons/hear.png')

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

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    Image 是一个StatefulWidgetImage.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); 
    

    【讨论】:

      【解决方案2】:

      感谢@diegoveloper 从flutter version 2.5 开始,建议使用带有const 修饰符的Image StatefulWidget,而Image.asset 是不可能的。但是,您需要将image path 作为参数提供给AssetImage 对象,其中该对象是Image StatefulWidget命名参数“图像”的值,如下所示.

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

      来自推荐 Dart 教程Dart Apprentice const and final 对象修饰符减少后续编译时间和运行时间。 因此,对于简洁且几行的代码,请使用Image.asset,但对于快速且对CPU友好的代码,请使用Image StatefulWidget

      【讨论】:

        猜你喜欢
        • 2023-01-26
        • 2019-06-21
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        • 2020-07-17
        • 2020-09-20
        • 2021-09-06
        • 2020-01-21
        相关资源
        最近更新 更多