首页 > 解决方案 > fromCsv 返回一个无法打开的文件异常

问题描述

我正在尝试使用ml_algo包使用ml_algo包中的 fromCsv 方法获取数据集。我已将 csv 文件放入资产文件夹中,但仍然出现错误。我已经尝试了所有可能的方法,从flutter clean到使缓存无效并重新启动,甚至尝试将它放在我的手机上,我给出了绝对路径,但它仍然不起作用

以下是飞镖代码:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:ml_dataframe/ml_dataframe.dart';
import 'package:ml_preprocessing/ml_preprocessing.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:permission/permission.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Future<void> initialiseDataframe() async {
   /* var permissionsRequested = await Permission.requestSinglePermission(PermissionName.Storage);
    print(permissionsRequested);
    var permissionsStatus = await Permission.getSinglePermissionStatus(PermissionName.Storage);
    print(permissionsStatus.toString());
    */
  Directory tempDir = await getTemporaryDirectory();
  String tempdir = tempDir.absolute.path;
  print(tempdir);

    final String directory = await ExtStorage.getExternalStorageDirectory();
    print(directory);
    final dataFrame = await fromCsv('wheat.csv',
        headerExists: true,
        columns: [2,3,5,6,7,8,9,10,11,12,13,14,15,16,
          17,18,19,20,21,22,23,24,25]);
    final normaliser = Normalizer();
    final transformedDataset = normaliser.process(dataFrame);
    print(transformedDataset.toMatrix());
  }
  @override
  void initState() {
    initialiseDataframe();

  }
}

这是 pubspec.yaml 文件

name: linear_regression
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  ml_dataframe: ^0.0.11
  ml_preprocessing: ^5.0.1
  ml_algo: ^13.3.7
  ext_storage: ^1.0.2
  permission: ^0.1.5
  path_provider: ^1.6.1


dev_dependencies:
  flutter_test:
    sdk: flutter


# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
  - assets/res/wheat.csv
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

和错误堆栈

E/flutter (26103): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'asset/res/wheat.csv' (OS Error: No such file or directory, errno = 2)
E/flutter (26103): #0      _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9)
E/flutter (26103): #1      _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter (26103): #2      _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (26103): #3      _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
E/flutter (26103): #4      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
E/flutter (26103): #5      Future._propagateToListeners (dart:async/future_impl.dart:709:32)
E/flutter (26103): #6      Future._completeWithValue (dart:async/future_impl.dart:524:5)
E/flutter (26103): #7      Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:554:7)
E/flutter (26103): #8      _rootRun (dart:async/zone.dart:1126:13)
E/flutter (26103): #9      _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (26103): #10     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (26103): #11     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
E/flutter (26103): #12     _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter (26103): #13     _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter (26103): 

标签: flutter

解决方案


问题是您尝试使用其绝对路径访问数据集,但您使用的路径是错误的,因为它在运行时已更改。不幸的是,Flutter 没有在运行时为我们提供其资产的正确绝对路径。

ml_algo 15.6.3 和 ml_dataframe 0.4.0 中有一个问题的解决方案:您需要使用读取数据集资产rootBundle.loadString并将结果字符串提供给DataFrame.fromRawCsv(...)构造函数:

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

final rawCsvContent = await rootBundle.loadString('assets/res/wheat.csv');
final samples = DataFrame.fromRawCsv(rawCsvContent);

推荐阅读