【问题标题】:How to fix undefined File() class and its methods in Dart?如何在 Dart 中修复未定义的 File() 类及其方法?
【发布时间】:2019-04-14 20:50:47
【问题描述】:

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

我尝试了一些网站的示例代码 sn-ps。没有任何效果。我的 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】:

    您已经创建了自己的名为File 的类,这样就可以从dart:io 中隐藏File 类。将您的自定义类命名为其他名称,或者执行以下操作:

    import 'dart:io' as io;

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


    原答案

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

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

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

    【讨论】:

    • 但它在我的 android 颤振项目中也不起作用。我在 VSCode 中遇到类似 Dartpad 的错误
    • @SyedMushaheed 仔细查看您的代码后,我发现了问题所在。我已经更新了我的答案。
    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多