how to create a directory in flutter

import 'package:path_provider_ex/path_provider_ex.dart';
import 'dart:io';
import 'package:simple_permissions/simple_permissions.dart';
//packages
//  simple_permissions: ^0.1.9
//  path_provider_ex:
//Android mainfest 
//  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 //   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
main(){
  List<StorageInfo> _storageInfo = [];

  @override
  void initState() {
    super.initState();
    initPlatformState();
    Timer(Duration(seconds: 2), () {
      createFolder();
    });
  }
  createFolder() async {
    PermissionStatus permissionResult =
        await SimplePermissions.requestPermission(
            Permission.WriteExternalStorage);
    if (permissionResult == PermissionStatus.authorized) {
    //   Directory _appFile = Directory(_storageInfo[0].rootDir + '/MyTestFOlder');
    // _appFile.create();
     new Directory(_storageInfo[0].rootDir + '/MyCreatedFolder').create()
    // The created directory is returned as a Future.
    .then((Directory directory) {
      print(directory.path);
  });
      // File ourTempFile = File(_appFile.path);
      // print(ourTempFile.path);
     // ourTempFile.create();
      // code of read or write file in external storage (SD card)
    }
  }
}

It is well explained in flutter documentation:

import 'dart:io';

void main() {
  new Directory('sensei-wa-koi-o-oshie-rarenai-chapter-7-bahasa-indonesia').create()
    // The created directory is returned as a Future.
    .then((Directory directory) {
      print(directory.path);
  });
}

However, in many situations, like creating one directory, perhaps the async (default) version of Directory.create will not be time saving and could perhaps result in race condition. In that case, using the sync version of the command would be more appropriate:

new Directory('sensei-wa-koi-o-oshie-rarenai-chapter-7-bahasa-indonesia').createSync()
// ... following sequential code

Of note, many dart::io methods have *Sync versions.

Tags:

Flutter