플러터(Flutter)로 앱을 개발할 때, 종종 앱 내부 저장소에 디렉토리를 생성해야 할 수 있습니다. 이 글에서는 플러터에서 앱 내부 저장소에 디렉토리를 생성하는 방법을 알아보겠습니다.
1. path_provider 패키지 설치하기
먼저, 앱 내부 저장소에 접근하기 위해서는 path_provider
패키지를 사용해야 합니다. 이 패키지는 앱의 특정 디렉토리 경로를 가져오는 기능을 제공합니다. 다음 명령을 터미널에 입력하여 패키지를 설치합니다.
flutter pub add path_provider
2. 디렉토리 경로 가져오기
path_provider
패키지를 사용하여 앱 내부 저장소의 디렉토리 경로를 가져옵니다. 다음과 같은 코드를 작성하세요:
import 'package:path_provider/path_provider.dart';
import 'dart:io';
Future<String> getLocalDirectoryPath() async {
Directory directory = await getApplicationDocumentsDirectory();
return directory.path;
}
getApplicationDocumentsDirectory()
함수를 호출하여 앱 내부 저장소의 경로를 가져옵니다. 이 함수는 dart:io
패키지에 있는 Directory
클래스의 인스턴스를 반환합니다.
3. 디렉토리 생성하기
이제 앱 내부 저장소에 새로운 디렉토리를 생성할 수 있습니다. 아래와 같이 코드를 작성하세요:
Future<void> createDirectory(String directoryName) async {
String localPath = await getLocalDirectoryPath();
String newPath = '$localPath/$directoryName';
Directory newDirectory = Directory(newPath);
newDirectory.create(recursive: true);
}
getLocalDirectoryPath()
함수를 사용하여 앱 내부 저장소의 경로를 가져옵니다. 이후, 새로운 디렉토리 경로를 설정합니다. Directory
클래스의 인스턴스를 이용하여 디렉토리를 생성하고, recursive
매개변수를 true
로 설정하여 필요한 경우 하위 디렉토리도 함께 생성합니다.
4. 디렉토리 생성 확인하기
디렉토리가 성공적으로 생성되었는지 확인하려면, 다음과 같은 코드를 작성하여 디렉토리가 존재하는지 확인할 수 있습니다:
bool isDirectoryExist(String directoryName) {
String localPath = getLocalDirectoryPath();
String directoryPath = '$localPath/$directoryName';
return Directory(directoryPath).existsSync();
}
getLocalDirectoryPath()
함수를 사용하여 앱 내부 저장소의 경로를 가져옵니다. 해당 경로에 새로운 디렉토리가 존재하는지 existsSync()
함수를 통해 확인합니다.
마무리
이제 앱 내부 저장소에 디렉터리를 생성하는 방법을 알았습니다. path_provider
패키지를 사용하여 앱 내부 저장소의 경로를 가져오고, Directory
클래스를 이용하여 새로운 디렉터리를 생성할 수 있습니다.
더 자세한 내용은 path_provider 패키지의 공식 문서를 참조하세요.