Flutter - SharedPreferences로 데이터 저장하기

유의선·2024년 3월 22일
0

SharedPreferences를 이용한 데이터 저장은 비교적 적은 양의 간단한 데이터를 저장하는 용도이다.

SharedPreferences 클래스를 이용하며, 이 클래스는 <키-값> 쌍으로 구성된 공유 환경설정 파일을 가리키며 이 파일에 데이터를 읽거나 쓰는 함수를 제공한다.


기본적으로 Flutter 프로젝트를 생성하면 데모 앱이 만들어지는데, 이 앱은 + 모양의 Floating Button을 누르면 화면의 값이 증가한다.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

그러나 앱을 종료하고 다시 실행하면 이 값은 0으로 초기화된다.

이 값을 SharedPreferences에 저장해 앱을 종료해도 숫자가 초기화되지 않도록 만들어보았다.


SharedPreferences 클래스를 손쉽게 사용하려면 shared_preferences 패키지를 이용한다.

pubspec.yaml 파일에 shared_preferences 패키지를 등록한다.

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  shared_preferences: 2.0.6

main.dart에 shared_preferences 패키지를 가져온다.

그리고 _MyHomePageState 클래스에 카운트값을 저장하는 함수 _setData()와 카운트값을 가져오는 함수 _loadData()를 만든다.
이 함수들은 언제 처리를 완료할지 예측할 수 없으므로 비동기 함수로 만들었다.

import 'package:shared_preferences/shared_preferences.dart';

...

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _setData(int value) async {
    var key = 'count';
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setInt(key, value);
  }

  void _loadData() async {
    var key = 'count';
    SharedPreferences pref = await SharedPreferences.getInstance();
    setState(() {
      var value = pref.getInt(key);
      if(value == null){
        _counter = 0;
      }else{
        _counter = value;
      }
    });
  }
  
  ...

_setData() 에서는
SharedPreferences 클래스의 인스턴스를 생성한 후 setInt() 함수를 통해 데이터를 저장한다.
setInt()key값으로는 'count', value 값으로는 매개변수를 설정하였다.
이것으로 'count' 라는 키에 대응하는 값이 SharedPreferences에 저장된다.

_loadData() 함수에서는
SharedPreferences 클래스의 인스턴스를 생성한 후 getInt() 함수를 통해 데이터를 불러온다.
getInt()key값으로는 'count'를 설정해 'count' 라는 키에 대응하는 값을 가져온다.
이렇게 가져온 데이터가 null이 아니면 _counter 변수에 이 데이터를 넣는다.


_setData() 함수와 _loadData() 함수를 호출한다.

카운트값을 가져오는 _loadData() 함수는 앱이 처음 실행될 때 호출하도록 initState() 함수에 넣고,
카운트 값을 저장하는 _setData() 함수는 버튼을 누를 때마다 호출되는 _incrementCounter() 함수의 _counter++ 코드 다음에 넣었다.

class _MyHomePageState extends State<MyHomePage> {

	...

  
  void initState() {
    super.initState();
    _loadData();
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
      _setData(_counter);
    });
  }

이것으로 앱을 종료한 후, 다시 켜도 카운트값이 그대로 유지된다.

0개의 댓글