안녕하세요! 오늘은 Flutter에서 앱 외부 저장소의 디렉토리를 삭제하는 방법에 대해 알아보겠습니다.
플러터에서는 path_provider
패키지를 사용하여 디렉토리의 경로를 얻고, dart:io
라이브러리를 사용하여 디렉토리를 삭제할 수 있습니다.
1. path_provider 패키지 추가하기
먼저, pubspec.yaml
파일에 path_provider
패키지를 추가해야 합니다. 다음과 같이 dependencies
섹션에 패키지를 추가합니다:
dependencies:
flutter:
sdk: flutter
path_provider: ^2.2.2
저장 후, 패키지를 다운로드하도록 터미널에서 flutter pub get
명령어를 실행해주세요.
2. 앱 외부 저장소 디렉토리 경로 얻기
다음으로는 앱 외부 저장소의 디렉토리 경로를 얻어야 합니다. 이를 위해 getExternalStorageDirectory()
함수를 사용합니다. 다음 코드를 참고해주세요:
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Delete Directory Example'),
),
body: Center(
child: ElevatedButton(
child: Text('Delete Directory'),
onPressed: () async {
Directory directory = await getExternalStorageDirectory();
String path = directory.path;
// Delete the directory
directory.delete(recursive: true);
print('Directory deleted: $path');
},
),
),
);
}
}
이 코드는 getExternalStorageDirectory()
함수를 호출하여 앱 외부 저장소의 디렉토리 경로를 얻고, directory.delete()
함수를 사용하여 디렉토리를 삭제합니다. 삭제할 때 recursive
옵션을 true
로 설정하면 하위 디렉토리와 파일도 함께 삭제됩니다.
3. 디렉토리 삭제 결과 확인하기
디렉토리 삭제 후에는 출력으로 경로가 제대로 삭제되었는지 확인하는 것이 좋습니다. 위 코드에서는 print()
함수를 사용하여 삭제한 경로를 출력합니다. 플러터 디버그 콘솔에서 확인할 수 있습니다.
이제 플러터 앱을 실행하고 “Delete Directory” 버튼을 클릭하면 앱 외부 저장소의 디렉토리가 삭제됩니다.
마무리
이번 포스트에서는 플러터에서 앱 외부 저장소의 디렉토리를 삭제하는 방법을 알아보았습니다. path_provider
패키지와 dart:io
라이브러리를 사용하여 앱 외부 저장소의 디렉토리 경로를 얻고, 디렉토리를 삭제하는 방법을 배웠습니다.
더 자세한 내용은 path_provider 패키지 문서를 참고해주세요.