操作系统错误:无此类文件或目录,errno = 2

时间:2019-09-11 07:36:59

标签: html string flutter dart

我无法加载存储在资产文件夹中的html文件。我已经搜寻了2天,但似乎找不到原因。

我已经确保也将其包含在pubspec.yaml中,并带有适当的缩进和全部-可以正常构建。我在pubspec.yaml中加载的图像资产没有问题,因此我知道该部分应该没问题。

我还尝试按照下面的确切示例代码使用.txt文件进行测试:https://api.flutter.dev/flutter/dart-io/File-class.html-来自“从文件读取”中的流部分。它给出了相同的错误。

这就是我想要做的:

// Tried this with a test .txt file too ('assets/html/test.txt')
File file = new File('assets/html/emaiL_bank.html');

Stream<List<int>> inputStream = file.openRead();
inputStream
    .transform(utf8.decoder)
    .transform(new LineSplitter())
    .forEach((l) => print('testing Print: $l'));

这是我的pubspec.yaml的一部分:

flutter:
  assets:
    - assets/images/ic_splashscreen.jpg
    - assets/images/at.png
    - assets/images/lock.png
    - assets/html/emaiL.html
    - assets/html/emaiL_bank.html
    - assets/html/test.txt

..并且我得到操作系统错误:没有这样的文件或目录,errno = 2 当它试图做file.openRead()

尝试清理干净,重新启动IDE,重新构建-似乎没有任何效果。

任何帮助/线索将不胜感激。

1 个答案:

答案 0 :(得分:1)

请使用rootBundle加载资产 https://flutter.dev/docs/development/ui/assets-and-images

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

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}

如果您尝试加载html文件以进行Web查看,请参考此https://inducesmile.com/google-flutter/how-load-a-local-html-file-in-flutter-webview/

Future<String> _loadLocalHTML() async {
  return await rootBundle.loadString('assets/html_code.html');
}

参考文档中的代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'dart:async';

class LoadHTMLFileToWEbView extends StatefulWidget {
  @override
  _LoadHTMLFileToWEbViewState createState() => _LoadHTMLFileToWEbViewState();
}

class _LoadHTMLFileToWEbViewState extends State<LoadHTMLFileToWEbView> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: _loadLocalHTML(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return WebviewScaffold(
            appBar: AppBar(title: Text("Load HTM file in WebView")),
            withJavascript: true,
            appCacheEnabled: true,
            url: new Uri.dataFromString(snapshot.data, mimeType: 'text/html')
                .toString(),
          );
        } else if (snapshot.hasError) {
          return Scaffold(
            body: Center(
              child: Text("${snapshot.error}"),
            ),
          );
        }
        return Scaffold(
          body: Center(child: CircularProgressIndicator()),
        );
      },
    );
  }
}

Future<String> _loadLocalHTML() async {
  return await rootBundle.loadString('assets/html_code.html');
}