dart 在Android中使用Flutter应用程序创建文件夹时出错

u1ehiz5o  于 2023-06-19  发布在  Android
关注(0)|答案(1)|浏览(148)

我需要在移动的的内部存储中创建一个文件夹,并命名。当我尝试创建一个文件夹时,我得到一个类似于FileSystemException的错误:创建失败,路径=“/storage/emulated/0/wizApp”(操作系统错误:不允许操作,错误号= 1)
这个文件夹创建的my dart代码

import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

// void exportData(List<Map<String, dynamic>> data) async {
//   final directory = await getExternalStorageDirectory();
//   print('Download directory: ${directory.path}'); // Print the directory path

//   final file = File('${directory.path}/data.json');
//   final jsonData = jsonEncode(data);
//   await file.writeAsString(jsonData);

//   print('Data exported successfully!');
// }

Future<bool> saveData(List<Map<String, dynamic>> data, String fileName) async {
  Directory directory;
  try {
    if (Platform.isAndroid) {
      if (await _requestPermission(Permission.storage)) {
        directory = await getExternalStorageDirectory();
        String newPath = "";
        print(directory);
        List<String> paths = directory.path.split("/");
        for (int x = 1; x < paths.length; x++) {
          String folder = paths[x];
          if (folder != "Android") {
            newPath += "/" + folder;
          } else {
            break;
          }
        }
        newPath = newPath + "/wizApp";
        directory = Directory(newPath);
      } else {
        return false;
      }
    } else {
      if (await _requestPermission(Permission.photos)) {
        directory = await getTemporaryDirectory();
      } else {
        return false;
      }
    }
    File saveFile = File(directory.path + "/$fileName");
    if (!await directory.exists()) {
      await directory.create(recursive: true);
    }
    if (await directory.exists()) {
      final file = File('${directory.path}/data.json');
      final jsonData = jsonEncode(data);
      await file.writeAsString(jsonData);

      print('Data exported successfully!');
      if (Platform.isIOS) {
        await ImageGallerySaver.saveFile(saveFile.path,
            isReturnPathOfIOS: true);
      }
      return true;
    }
    return false;
  } catch (e) {
    print(e);
    return false;
  }
}

Future<bool> _requestPermission(Permission permission) async {
  if (await permission.isGranted) {
    return true;
  } else {
    var result = await permission.request();
    if (result == PermissionStatus.granted) {
      return true;
    }
  }
  return false;
}

这是我的清单文件设置

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.blockly">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <!-- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
    tools:ignore="ScopedStorage" /> -->
   <application
        android:label="Wizklub IoT App"
        android:icon="@mipmap/ic_launcher"
         android:requestLegacyExternalStorage="true"
         android:usesCleartextTraffic="true">
         
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
                
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>
bzzcjhmw

bzzcjhmw1#

您指定了内部存储,它是正确的信息吗?因为看起来您正在尝试在外部存储器上写入。
您可以简单地使用此示例进行内部存储写入:

import 'dart:io';

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

class CreateFolder extends StatelessWidget {
  const CreateFolder({super.key});

  Future<String?> createNewFolder() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final folderPath = '${directory.path}/MyFolder';

      final folder = Directory(folderPath);
      await folder.create(recursive: true);
      print("Folder created at: $folderPath");
      return folderPath;
    } catch (e) {
      print('Error creating folder: $e');
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () {
          createNewFolder();
        },
        child: Text("Create folder"),
      ),
    );
  }
}

相关问题