Flutter 1.0-无法加载文本资产

时间:2018-12-23 16:07:23

标签: flutter

我无法在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中的asset部分

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

我在某个愚蠢的地方犯错了吗? 为您拥有的所有指针欢呼。

Project Structure

如果您想看一眼,这里是代码的临时副本。 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)

1 个答案:

答案 0 :(得分:0)

资产访问可以与您问题中的pubspec.yaml配合使用。

new Text(“ Name:” + toon.info.name))

失败,因为toonnull,因为它从未分配值。

您可以使用new Text("Name: " + (toon?.info?.name ?? 'foo')),来解决该异常。

如果添加

widget.storage.getFileData('toonRepo/data.json').then((f) => print(f));

转到_FlutterDemoState.initState(),您会看到读取资产的效果很好。