如何在Dart中修复未定义的File()类及其方法?

问题描述 投票:0回答:1

我想将文件保存在Android / iOS的本地存储中。我按照Flutter食谱来保存文件,但它没有用。有各种使用File类的例子,但是当我使用它时它是未定义的。我正在使用Dart 2.2.0和Flutter 1.2.1

我试过几个网站的示例代码片段。没有任何效果。我的Dart文件中未定义文件类,readAsStringwriteAsString

这是代码。在DartPad中查看。我哪里错了?

//packages
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';

//start
class File {
  /// Directory Path
  /// Local Directory Path
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    // For your reference print the AppDoc directory
    print(directory.path);
    return directory.path;
  }
  /// Reference for file Location
  Future<File> get _localFile async {
    final path = await _localPath;
    final address = '$path/data.txt';
    return File(address);
  }
  /// Presenting different Data as 1 String
  String convertingtoString(String title, String author, String content) {
    return '$title\n$author\n\n$content';
  }
  /// Write to file
  /// Writing as String
  Future<File> writeContent(String matter) async {
    /// Get matter converted to string as matter
    final file = await _localFile;
    // Write the file
    return file.writeAsString(matter);
  }
  /// Read from file
  Future<String> readcontent() async {
    try {
      final file = await _localFile;
      // Read the file
      String contents = await file.readAsString();
      return contents;
    } catch (e) {
      // If there is an error reading, return a default String
      return 'Error, Couldn\'t read file';
    }
  }
}

这是我的android flutter项目的代码。我在VScode中得到了像DartPad一样的错误

dart
1个回答
0
投票

您已经创建了自己的名为File的类,因此隐藏了File中的dart:io类。将自定义类命名为其他类,或执行以下操作:

import 'dart:io' as io;

并使用io.File,你打算使用dart:ioFile类。 (我建议重命名自定义类以避免混淆。)


原始答案

既然你有import 'dart:io';,那么你应该可以使用File课程。

如果你只是用DartPad尝试这个,那么它(除其他外)将无法在那里工作,因为dart:io is meant to be used with a Dart VMdart:io不能在具有沙盒环境的浏览器中工作,并且通常会阻止文件系统访问:

重要提示:基于浏览器的应用程序无法使用此库。只有服务器,命令行脚本和Flutter移动应用程序可以导入和使用dart:io。

© www.soinside.com 2019 - 2024. All rights reserved.