扑。文件 containsSync() 始终返回 false

Isa*_*aac 6 assets file dart dart-io flutter

这就是我现在面临的问题。我有一个名为“assets”的文件夹,在该文件夹内有一个名为“no_icon.png”的图像。我已将其添加到 pubspec.yaml 中,如下所示:

flutter:
  assets:
    - assets/teamShields/
    - assets/no_icon.png
Run Code Online (Sandbox Code Playgroud)

当我在 StatelessWidget 中执行此操作时

final imageP = File('assets/no_icon.png');
Run Code Online (Sandbox Code Playgroud)

然后在这个和一个 MaterialApp 里面:

body: Text(imageP.existsSync().toString()),
Run Code Online (Sandbox Code Playgroud)

我总是在屏幕上看到错误。

另外,如果我输入Image.asset('assets/no_icon.png'),而不是文本,我可以看到渲染的图像。

我不知道这是一个错误还是我做错了什么......

rmt*_*zie 2

您应该使用 Flutter 的资产支持,而不是使用文件。它旨在处理您在 pubspec 文件中声明的任何资产。

如果从有状态/无状态小部件使用,则看起来像这样:

Future<ByteData> loadFile(context) async {
  AssetBundle bundle = DefaultAssetBundle.of(context).bundle;
  try {
    return await bundle.load("path/to.file");
  } catch (e) {
    print("Failed to load file because of $e");
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以从任何有意义的地方调用它,即 initState 或使用 FutureBuilder。或者您可以使用:

import 'package:flutter/services.dart' show rootBundle;

...

Future<ByteData> loadAsset() async {
  return await rootBundle.load('assets/some.file');
}
Run Code Online (Sandbox Code Playgroud)

但是,您似乎正在尝试加载存在特殊情况的图像文件。

来自文档

Widget build(BuildContext context) {
  // ...
  return DecoratedBox(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('graphics/background.png'),
        // ...
      ),
      // ...
    ),
  );
  // ...
}
Run Code Online (Sandbox Code Playgroud)

您所需要做的就是使用 AssetImage =)。