【发布时间】:2019-05-23 03:00:59
【问题描述】:
我在 Flutter (1.0) 中加载文本资源时遇到了一些问题。 这是当前试图读取资产的代码。
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
Future<File> get _localFile async {
final path = await _localPath;
final file = File('$path/toon_test_3.json');
bool exists = file.existsSync();
if(exists){
return file;
} else {
// Load the default file
final newfile = await getFileData('toonRepo/data.json');
return file.writeAsString(newfile);
}
}
loadString 将失败弹出以下内容:
Could not load source 'dart:core/runtime/libobject_patch.dart': <source not available>.
如果继续执行,则会引发以下异常:
Exception has occurred.
FlutterError (Unable to load asset: toonRepo/data.json)
我在这里尝试了很多围绕 pubspec.yaml 中资产部分的解决方案
name: hello_world
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
path_provider: ^0.4.1
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
english_words: ^3.1.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
assets:
- toonRepo/
uses-material-design: true
我是不是在某个非常愚蠢的地方出错了? 为你的任何指点干杯。
如果您想看一看,这里是代码的临时副本。 Github
这是一个堆栈跟踪
[VERBOSE-2:shell.cc(184)] Dart Error: Unhandled exception:
Unable to load asset: toonRepo/data.json
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:67:33)
<asynchronous suspension>
#2 CachingAssetBundle.loadString.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:162:56)
#3 __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:284:23)
【问题讨论】:
-
data.json文件相对于pubspec.yaml的路径是什么。是toonRepo/data.json或assets/toonRepo/data.json还是别的什么? -
toonRepo/data.json。它在项目根目录中。我已经添加了结构图片,以防我比平时更白痴。
-
你试过
flutter clean吗? -
是的,我怕干净不快乐。
-
如果在
pubspec.yaml中添加完整的文件路径而不是只添加目录会怎样?
标签: flutter