Flutter读取本地文件目录

通过path_provider_android:^2.0.17

dependencies:
 flutter:
    sdk: flutter
  path_provider_android: ^2.0.17

官方示例代码

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'package:flutter/material.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Path Provider',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Path Provider'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State {
  final PathProviderPlatform provider = PathProviderPlatform.instance;
  Future? _tempDirectory;
  Future? _appSupportDirectory;
  Future? _appDocumentsDirectory;
  Future? _externalDocumentsDirectory;
  Future?>? _externalStorageDirectories;
  Future?>? _externalCacheDirectories;

  void _requestTempDirectory() {
    setState(() {
      _tempDirectory = provider.getTemporaryPath();
    });
  }

  Widget _buildDirectory(
      BuildContext context, AsyncSnapshot snapshot) {
    Text text = const Text('');
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasError) {
        text = Text('Error: ${snapshot.error}');
      } else if (snapshot.hasData) {
        text = Text('path: ${snapshot.data}');
      } else {
        text = const Text('path unavailable');
      }
    }
    return Padding(padding: const EdgeInsets.all(16.0), child: text);
  }

  Widget _buildDirectories(
      BuildContext context, AsyncSnapshot?> snapshot) {
    Text text = const Text('');
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasError) {
        text = Text('Error: ${snapshot.error}');
      } else if (snapshot.hasData) {
        final String combined = snapshot.data!.join(', ');
        text = Text('paths: $combined');
      } else {
        text = const Text('path unavailable');
      }
    }
    return Padding(padding: const EdgeInsets.all(16.0), child: text);
  }

  void _requestAppDocumentsDirectory() {
    setState(() {
      _appDocumentsDirectory = provider.getApplicationDocumentsPath();
    });
  }

  void _requestAppSupportDirectory() {
    setState(() {
      _appSupportDirectory = provider.getApplicationSupportPath();
    });
  }

  void _requestExternalStorageDirectory() {
    setState(() {
      _externalDocumentsDirectory = provider.getExternalStoragePath();
    });
  }

  void _requestExternalStorageDirectories(StorageDirectory type) {
    setState(() {
      _externalStorageDirectories =
          provider.getExternalStoragePaths(type: type);
    });
  }

  void _requestExternalCacheDirectories() {
    setState(() {
      _externalCacheDirectories = provider.getExternalCachePaths();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView(
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                onPressed: _requestTempDirectory,
                child: const Text('Get Temporary Directory'),
              ),
            ),
            FutureBuilder(
                future: _tempDirectory, builder: _buildDirectory),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                onPressed: _requestAppDocumentsDirectory,
                child: const Text('Get Application Documents Directory'),
              ),
            ),
            FutureBuilder(
                future: _appDocumentsDirectory, builder: _buildDirectory),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                onPressed: _requestAppSupportDirectory,
                child: const Text('Get Application Support Directory'),
              ),
            ),
            FutureBuilder(
                future: _appSupportDirectory, builder: _buildDirectory),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                onPressed: _requestExternalStorageDirectory,
                child: const Text('Get External Storage Directory'),
              ),
            ),
            FutureBuilder(
                future: _externalDocumentsDirectory, builder: _buildDirectory),
            Column(children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: ElevatedButton(
                  child: const Text('Get External Storage Directories'),
                  onPressed: () {
                    _requestExternalStorageDirectories(
                      StorageDirectory.music,
                    );
                  },
                ),
              ),
            ]),
            FutureBuilder?>(
                future: _externalStorageDirectories,
                builder: _buildDirectories),
            Column(children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: ElevatedButton(
                  onPressed: _requestExternalCacheDirectories,
                  child: const Text('Get External Cache Directories'),
                ),
              ),
            ]),
            FutureBuilder?>(
                future: _externalCacheDirectories, builder: _buildDirectories),
          ],
        ),
      ),
    );
  }
}

在运行其代码之前还是要在Android代码中加上权限代码

/android/app/src/mai/AndroidManifest.xml中添加


    
      
    
    


   
        
            
            
            
                
                
            
        
        
        
    

Flutter读取本地文件目录_第1张图片Flutter读取本地文件目录_第2张图片

 

 

结果如下

provider.getTemporaryPath()=》path: /data/user/0/com.example.read_database/cache
provider.getApplicationDocumentsPath()=》path: /data/user/0/com.example.read_database/app_flutter
provider.getApplicationSupportPath()=》path: /data/user/0/com.example.read_database/files
provider.getExternalStoragePath()=》path: /storage/emulated/0/Android/data/com.example.read_database/files
// type此处传入的是StorageDirectory.music
provider.getExternalStoragePaths(type: type)=>paths: /storage/emulated/0/Android/data/com.example.read_database/files/music
provider.getExternalCachePaths()=>paths: /storage/emulated/0/Android/data/com.example.read_database/cache

你可能感兴趣的:(flutter,android,android,studio)