【问题标题】:Why does the File class return an object of type '_File' instead of 'File' in Dart/Flutter?为什么 File 类在 Dart/Flutter 中返回类型为 '_File' 而不是 'File' 的对象?
【发布时间】:2022-01-19 06:57:55
【问题描述】:

没有什么可说的了。我创建了一个没有依赖项的空白项目来测试它。

如果您想自己运行,请复制代码:

import 'dart:io';

void main() {
  File testFile = File('test');
  print('testFile: $testFile');
  print('testFile type: ${testFile.runtimeType}');
  print(testFile.runtimeType == File);
  print('');
}

编辑:将颤振升级到 2.8.0,同样的问题仍然存在。

【问题讨论】:

  • testFile is File 将是true,这是检查对象类型的正确方法。一般来说,您不应该依赖runtimeType(尤其是对于您无法控制的类),因为它可能是某个派生类。
  • @jamesdlin 另一个答案在技术上直接回答了我的问题,但你的更有帮助。感谢您解释我真正需要知道的内容!

标签: flutter dart dart-io


【解决方案1】:

File 是抽象类。 _File 是 File 的实现。所以在这种情况下,testFile 的 runtimeType 是_Type。

@pragma("vm:entry-point")
abstract class File implements FileSystemEntity {
  /// Creates a [File] object.
  ///
  /// If [path] is a relative path, it will be interpreted relative to the
  /// current working directory (see [Directory.current]), when used.
  ///
  /// If [path] is an absolute path, it will be immune to changes to the
  /// current working directory.
  @pragma("vm:entry-point")
  factory File(String path) {
    final IOOverrides? overrides = IOOverrides.current;
    if (overrides == null) {
      return new _File(path);
    }
    return overrides.createFile(path);
  }

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2013-08-20
    • 2013-11-10
    • 2021-08-12
    相关资源
    最近更新 更多