일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- texttheme
- import
- Collection
- crawler
- 클래스
- function
- set
- python
- 코틀린
- ML
- map
- textstyle
- 다트
- List
- package
- 크롤러
- 웹크롤러
- text
- 파이썬
- Android
- DART
- 함수
- 콜렉션
- kotlin
- Flutter
- pushnamed
- variable
- Class
- 플러터
- animation
- Today
- Total
조용한 담장
Flutter : path_provider 본문
path_provider, read and write files
Flutter 의 path_provider package 와 dart:io library (File, Directory) 를 이용해 파일을 쓰고 지우는 방법을 보자.
path_provider
앱이 일반적으로 사용하는 저장 위치들을 얻을 수 있는 패키지 이다.
- Temporary directory: 캐쉬같이 임시로 데이터를 저장하는 공간이고 언제든지 삭제될 수 있다. iOS 의 NSCachesDirectory와 Android 의 getCacheDir() 의 값에 해당하는 위치이다.
- Documents directory: 해당 앱만의 저장공간이며 앱이 삭제되면 없어진다. iOS 의 NSDocumentDirectory 와 Android 의 AppData 값에 해당한다.
functions
아래의 함수들을 통해 일반적인 앱이 접근하여 사용하는 저장공간에 해당하는 파일 시스템상의 위치 정보를 얻을 수 있다.
- getApplicationDocumentsDirectory()
- getApplicationSupportDirectory()
- getExternalCacheDirectories()
- getExternalStorageDirectories({StorageDirectory type })
- getExternalStorageDirectory()
- getLibraryDirectory()
- getTemporaryDirectory()
dart:io library
File, socket, HTTP, and other I/O support for non-web applications.
I/O 관련된 기능들을 지원하는 dart 언어의 기본 라이브러리 이다.
여기서는 파일 입출력이 관련된 기능만 사용해 본다.
File class
File(String path)
A reference to a file on the file system.
파일 시스템상의 파일을 참조하는 클래스 이다. 파일의 주소를 가지고 파일 쓰기, 읽기, 지우기 등의 여러가지 일을 할 수 있다.
Directory class
Directory(String path)
A reference to a directory (or folder) on the file system.
파일 시스템 상의 디렉토리(폴더) 를 참조하는 클래스 이다. 디렉토리의 주소를 가지고 디렉토리를 생성하거나 하위 디렉토리, 파일 등의 정보를 가져오는 등의 일을 할 수 있다.
Example

TextField 에 입력한 문자열을 파일에 저장한 후 읽어오는 동작이다.
class MessageStorage { | |
final _fileName; | |
String _path; | |
MessageStorage(this._fileName) { | |
init(); | |
} | |
void init() async { | |
final directory = await getApplicationDocumentsDirectory(); | |
_path = directory.path; | |
} | |
Future<String> readFile() async { | |
try { | |
final file = File('$_path/$_fileName'); | |
return file.readAsString(); | |
} catch (e) { | |
return e.toString(); | |
} | |
} | |
Future<void> writeFile(String message) async { | |
try { | |
final file = File('$_path/$_fileName'); | |
file.writeAsString(message); | |
} catch(e){ | |
print(e); | |
} | |
} | |
} |
파일 저장에 관련된 기능을 구현한 클래스 이다.
init()
을 통해 입력받은 파일명과 getApplicationDocumentsDirectory()
의 경로인 Directory.path
값을 합쳐 저장경로('$_path/$_fileName')로 쓴다.
파일을 읽는 함수와 문자열 데이터를 파일에 쓰는 함수가 있다.
아래는 UI를 구성하는 코드이다.
class _MyHomePageState extends State<MyHomePage> { | |
MessageStorage storage = MessageStorage('message.txt'); | |
String message = ''; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
// ... | |
body: SingleChildScrollView( | |
child: Center( | |
child: Column( | |
children: <Widget>[ | |
Text( | |
'Write message to save', | |
style: TextStyle(fontSize: 20.0), | |
), | |
TextField( | |
decoration: InputDecoration( | |
border: OutlineInputBorder(), | |
), | |
onSubmitted: (text) { | |
storage.writeFile(text); | |
}, | |
), | |
RaisedButton( | |
child: Text('Read file'), | |
onPressed: () { | |
storage.readFile().then((onValue) { | |
setState(() { | |
message = onValue; | |
}); | |
}); | |
}, | |
), | |
Text(message), | |
], | |
), | |
), | |
), | |
); | |
} | |
} |
Reference
'Flutter' 카테고리의 다른 글
Flutter : Asset (0) | 2019.11.20 |
---|---|
Flutter : shared_preferences (0) | 2019.11.11 |
Flutter : sqflite package (SQLite plugin) (1) | 2019.11.08 |
Flutter : permission_handler (0) | 2019.11.05 |
Flutter : DataTable (3) | 2019.11.04 |