【问题标题】:Flutter. File existsSync() always returns false扑。 File existsSync() 总是返回 false
【发布时间】:2019-03-10 05:14:31
【问题描述】:

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

flutter:
  assets:
    - assets/teamShields/
    - assets/no_icon.png

当我在 StatelessWidget 内做时

final imageP = File('assets/no_icon.png');

然后在这个里面还有一个 MaterialApp:

body: Text(imageP.existsSync().toString()),

我总是在我的屏幕上看到 false。

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

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

【问题讨论】:

  • 资产不是文件。它们是可执行文件中的捆绑包。
  • 查看AssetBundle
  • 我明白了,那么如何检查资产是否存在?还是应该使用文件?

标签: file dart flutter assets dart-io


【解决方案1】:

您应该使用 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;
  }
}

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

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

...

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

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

来自the docs

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

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

【讨论】:

  • 是的,但我试图阻止我的程序尝试加载不存在的资产。你知道怎么做吗?
  • 这并不是资产的真正含义......您需要准确地预定义哪些资产将包含在构建中,因此您的应用永远不应尝试加载不存在的资产(并且它确实,这是一个错误)。但是这样做的方法是正是我在答案的第一部分中描述的,在 loadFile 周围使用 try & catch。我不认为有这样做的同步方式,如果那是你想要做的。
  • 不一定要同步,但是尝试答案的第一部分会引发错误,就像忽略了 try catch 部分一样。我也试过用 catchError 还是一样
猜你喜欢
  • 2023-01-19
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
相关资源
最近更新 更多