Flutter - Hive를 사용해보자

RISTRETTO·2020년 5월 6일
0

Hive를 사용하면 앱 로컬에 데이터를 저장할 수 있다.
테마, 유저 설정, 로그인 데이터와 같이 앱을 껐다가 켜도 계속 유지하고 싶은 데이터가 있을 때
빠르고 초-간단한 Hive를 이용해보자 !

Step 1. pubspec.yaml에 패키지를 설치해줍니다.

dependencies:
  hive: ^1.4.1+1
  hive_flutter: ^0.3.0+2

Step 2. main.dart에서 init 설정을 해줍니다.

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  await Hive.initFlutter();
  await Hive.openBox('tutorial');
  runApp(MyApp());
}

main() 함수를 async함수로 바꿔주고 hive_flutter 패키지에서 불러온 initFlutter메서드를 호출합니다.
Hive에서는 로컬에 데이터를 담는 바구니(???) 단위가 Box입니다.
openBox메서드로 tutorial이라는 Box를 하나 만들어주었습니다.

이제 앱의 어디서든 tutorial이라는 로컬 데이터베이스에 데이터를 넣고 뺄수 있습니다!

ㅎㅎ 한번 해보겠습니다.

Step 3. 데이터 저장하기

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: Column(
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                Hive.box('tutorial').put('pizza_key', 'potato_pizza');
                setState(() {});
              },
              child: Text('로컬에 데이터 저장'),
            ),
          ],
        ),
      ),
    );
  }
}

Hive.box(박스이름)으로 방금 만든 tutorial박스를 불러오고 put메서드를 호출합니다.
Hive는 기본적으로 noSQL이기에 key-value로 데이터가 저장됩니다.
'pizza_key'라는 key에 'potato_pizza'라는 value를 저장하는 버튼을 만들었습니다.

Step 4. 데이터 불러오기

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String localData = Hive.box('tutorial').get('pizza_key');

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: Column(
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                Hive.box('tutorial').put('pizza_key', 'potato_pizza');
                setState(() {});
              },
              child: Text('로컬에 데이터 저장'),
            ),
            Container(
              child: Text(localData != null ? localData : '빈 텍스트'),
            )
          ],
        ),
      ),
    );
  }
}

클래스 상단에 localData라는 변수를 만들고 get메서드를 호출해서 데이터를 불러옵니다.
이제 버튼을 클릭해서 key-value를 로컬에 저장하면
앱을 껐다켜도 Container 위젯에 'potato_pizza' 라는 텍스트가 남아있을 것입니다.

다음 포스팅에는 Hive를 프로젝트에서 어떤식으로 사용할 수 있는지 소개해드리겠습니다.

profile
빛나는 개발자

0개의 댓글