플러터:데이터 저장(간단한 데이터)
둘러보기로 이동
검색으로 이동
개요[편집 | 원본 편집]
Flutter에서 화면을 이동하거나 앱을 재시작해도 데이터를 유지하려면 상태 관리와 로컬 저장 방법을 이해해야 한다.
이 문서에선 Hive를 이용한 로컬 DB 기반 데이터 저장에 대해 다룬다.
Hive의 특징[편집 | 원본 편집]
- 매우 빠름 (binary 기반)
- 리스트, Map, 객체까지 저장 가능(클래스 형태도 저장)
- 오프라인 DB 역할 수행
- iOS/Android 모두 지원
- 수백~수천 개 데이터 저장해도 빠름
Hive 저장 위치[편집 | 원본 편집]
| 운영체제 | 설명 | 비고 |
|---|---|---|
| 안드로이드 | /data/data/<패키지명>/files/hive/ |
|
| iOS | Application/<UUID>/Documents/hive/
(앱 UUID는 설치할 때마다 달라짐) |
|
| Windows | %APPDATA%\<앱폴더>\hive | 예시: C:\Users\<사용자>\AppData\Roaming\com.example.myapp\hive\ |
| 브라우저 | 파일이 아닌, IndexedDB 내부에 저장됨.
(Chrome 기준: 개발자도구 → Application → IndexedDB) F5 눌러도 저장된 값이 그대로 유지된다. |
(dart에서 작성한 box, decibelBox 등이 그대로 DB 이름이 됨)
|
Hive로 데이터 유지하기[편집 | 원본 편집]
준비[편집 | 원본 편집]
dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0
전체 코드[편집 | 원본 편집]
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
await Hive.openBox('box'); // 'box'라는 이름으로 열기. Hive의 Box는 작은 데이터베이스 하나라고 생각하면 됨.
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final box = Hive.box('box');
int count = 0;
@override
void initState() { // 앱 시작 시 초기화
super.initState();
count = box.get('count', defaultValue: 0); // 저장된 값 불러오기
}
void increase() {
setState(() {
count++;
box.put('count', count); // 저장
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Hive 초간단 예제")),
body: Center(child: Text("$count", style: TextStyle(fontSize: 40))),
floatingActionButton: FloatingActionButton(
onPressed: increase,
child: Icon(Icons.add),
),
),
);
}
}