簡體   English   中英

如何從 Flutter 的外部存儲中獲取文件?

[英]How to get files from external storage in Flutter?

我想使用 flutter 項目獲取列表視圖中的所有文件,但如何訪問外部文件夾。

我創建了一個名為“MyFile”的文件夾,它是在“/storage/emulated/0/MyFile”創建的,

但下面的代碼指向“/storage/emulated/0/Android/data/com.example.demo/MyFile”。

我不知道為什么下面的代碼不起作用

 Directory externalDirectory = await getExternalStorageDirectory();
 print('External Storage:$externalDirectory');
 // External storage: /storage/emulated/0/Android/data/com.example.demo/MyFile

使用 Flutter 官方path_provider package 時,getExternalStorageDirectory() 將始終返回到 /storage/emulated/0/ your-package-name /files 的路徑。

要獲取/storage/emulated/0/ ,您可以使用第三方 package ext_storage 下面的代碼將返回您想要的目錄路徑

 var externalDirectoryPath = await ExtStorage.getExternalStorageDirectory();
 print(path);  // /storage/emulated/0

現在要創建一個文件夾,您可以使用以下 function:

//this will create a Folder in the storage/emulated/0
new Directory(externalDirectoryPath +'/YourfolderName')
  .create()
  .then((Directory directory) 
  {
    print(directory.path);
  });;

'

編輯帖子圖片 2 以證明它有效。

用於創建目錄、文件的代碼片段

    new Directory('/storage/emulated/0/MyFile').create()
    // The created directory is returned as a Future.
        .then((Directory directory) {
      print(directory.path);
    });

    new File('/storage/emulated/0/MyFile/test.txt').create(recursive: true)
        .then((File file) {
      // Stuff to do after file has been created...
      print('${file.path}');
    });

    var dir = Directory('/storage/emulated/0/MyFile');
    print('${dir.path}');
    print('${dir.list().toList()}');

創建目錄和文件的完整代碼

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:simple_permissions/simple_permissions.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(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    new Directory('/storage/emulated/0/MyFile').create()
    // The created directory is returned as a Future.
        .then((Directory directory) {
      print(directory.path);
    });

    new File('/storage/emulated/0/MyFile/test.txt').create(recursive: true)
        .then((File file) {
      // Stuff to do after file has been created...
      print('${file.path}');
    });

    var dir = Directory('/storage/emulated/0/MyFile');
    print('${dir.path}');
    print('${dir.list().toList()}');


    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    SimplePermissions.requestPermission(Permission.WriteExternalStorage);

    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          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.
    );
  }
}

請使用 package flutter_file_manager https://pub.dev/packages/flutter_file_manager
我用真機測試過,效果很好

完整代碼

// framework
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';

// packages
import 'package:flutter_file_manager/flutter_file_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:simple_permissions/simple_permissions.dart';

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

@immutable
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //SimplePermissions.requestPermission(Permission.ReadExternalStorage);
    SimplePermissions.requestPermission(Permission.WriteExternalStorage);
    return new MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text("Flutter File Manager Demo"),
          ),
          body: FutureBuilder(
            future: _files(), // a previously-obtained Future<String> or null
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('Press button to start.');
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return Text('Awaiting result...');
                case ConnectionState.done:
                  if (snapshot.hasError)
                    return Text('Error: ${snapshot.error}');
                  return snapshot.data != null
                      ? ListView.builder(
                          itemCount: snapshot.data.length,
                          itemBuilder: (context, index) => Card(
                                  child: ListTile(
                                title: Column(children: [
                                  Text('Size: ' +
                                      snapshot.data[index]
                                          .statSync()
                                          .size
                                          .toString()),
                                  Text('Path: ' +
                                      snapshot.data[index].path.toString()),
                                  Text('Date: ' +
                                      snapshot.data[index]
                                          .statSync()
                                          .modified
                                          .toUtc()
                                          .toString())
                                ]),

                                subtitle: Text(
                                    "Extension: ${p.extension(snapshot.data[index].absolute.path).replaceFirst('.', '')}"), // getting extension
                              )))
                      : Center(
                          child: Text("Nothing!"),
                        );
              }
              return null; // unreachable
            },
          )),
    );
  }


  _files() async {
    var root = await getExternalStorageDirectory();
    var files = await FileManager(root: root).walk().toList();

    for(var i = 0;i<files.length;i++) {
      print("${files[i].path} ");
    }
      return files;
  }

}

在模擬器中工作演示

在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM