App/Flutter

dart.io 폴더 접근

브레인야또 2022. 9. 4. 23:11

1) path 사용을 위해 내부 import

- import 'dart:io'

- import 'package:path_provider/path_provider.dart'

1) 폴더 path 접근

- ios : getApplicationDocumentsDirectory();

- android : getExternalStorageDirectory();

2) 파일 list로 만들기    

- List<FileSystemEntity> list = Directory('/storage/emulated/0/DCIM').listSync();

3) 가져온 리스트 형식 검사

- 파일위치.runtimeType.toString()   ex : _File , _Directory

4) 폴더 없을때 생성 하기

import 'dart:io';

void main() async {
  // Creates dir/ and dir/subdir/.
  var directory = await Directory('dir/subdir').create(recursive: true);
  print(directory.path);
}

https://api.dart.dev/stable/2.18.0/dart-io/Directory/create.html

< 폴더 여부 확인 법 >

 

create method - Directory class - dart:io library - Dart API

Future create({bool recursive = false} ) Creates the directory if it doesn't exist. If recursive is false, only the last directory in the path is created. If recursive is true, all non-existing path components are created. If the directory already exists n

api.dart.dev

5) 폴더 찾아가며 파일 불러오는 예제

    List<FileSystemEntity> list = Directory('/storage/emulated/0/DCIM').listSync();

    List<FileSystemEntity> imgList = [];
    List<FileSystemEntity> fileList = [];
    List<String> directoryList = [''];

    int bingLen = 1;
    int len = list.length;
    List<FileSystemEntity> filelistArray = list;   
    int start = 1;

    for(int i = 0; i <bingLen; i++) {
      if( start != 1) {
        len = Directory('${directoryList[i]}').listSync().length;
        filelistArray = Directory('${directoryList[i]}').listSync();
      }

      start++;
      if(len > 0 ) {
        for (int y = 0; y <len; y++) {
          print('filelistArray : ${filelistArray[y]}');
          if (filelistArray[y].runtimeType.toString() == '_File') {
              fileList.add(filelistArray[y]);
          } else if(filelistArray[y].runtimeType.toString() == '_Directory') {
              directoryList.add('${filelistArray[y].path}');
          }
          // 마지막 회전때 
          if(y == len -1 && start != 2 ) {
            bingLen = directoryList.length;
          }
        }
      } else {
        continue;
      }
      // 마지막 회전때 
      if(i+1 == bingLen) {
        bingLen = directoryList.length;
      }

    }                        
    List<FileSystemEntity> dir = fileList;

    print(dir);
    return Scaffold(
      appBar: AppBar(title: Text('총 파일 갯수 : ${dir.length} 개', style: TextStyle(fontSize: 30, color: ColorConfig.black),)),
      body: SingleChildScrollView(
        child:GridView.builder(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          itemCount: dir.length,
          shrinkWrap: true,
          physics: ScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 20,
            crossAxisSpacing: 20,
          ),
          itemBuilder: (BuildContext context, int index) {
            return InkWell(
              onTap: () async {
                
                File file = File(dir[index].path.toString());
                var hi = SellService.upload('/upload/appImgUpload', [file]);
                print(hi);
                
              },
              child: Column(
                children: [
                  // Image.file(File(dir[index].path.toString()),
                  // width: 80,
                  // height: 80,
                  // fit: BoxFit.fill,
                  // ),
                  Text('${dir[index].path}', style: TextStyle(fontSize: 10, color: ColorConfig.black),)
                ],
              )
            );
          },
        ),
      ),
    );
  }