728x90

상대적으로 적은 양의 키-값 데이터를 저장하려고 한다면, shared_preferences 플러그인을 사용한다.

 

https://pub.dev/packages/shared_preferences/install 에서 최신 버전을 찾아서 pubspec.yaml 내에 추가한다.

dependencies:
  shared_preferences: ^2.0.15

 

Dart 코드에 아래 한줄을 import 한다.

import 'package:shared_preferences/shared_preferences.dart';

 

Save Data

// shared preferences 얻기
final prefs = await SharedPreferences.getInstance();
 
// 값 저장하기
prefs.setInt('counter', counter);

 

Read Data

// Save Data
final prefs = await SharedPreferences.getInstance();
prefs.setInt('counter'0);
prefs.setDouble('width'20.5);
prefs.setBool('isAdmin'true);
prefs.setString('userName''dev-yakuza');
prefs.setStringList('alphabet', ['a''b''c''d']);
 
// Read Data
final prefs = await SharedPreferences.getInstance();
final counter = prefs.getInt('counter') ?? 0;
final width = prefs.getDouble('width') ?? 10.5;
final isAdmin = prefs.getBool('isAdmin') ?? false;
final userName = prefs.getString('userName') ?? '';
final alphabet = prefs.getStringList('alphabet') ?? [];
final data = prefs.get('userInfo') : {};

 

Remove Data

final prefs = await SharedPreferences.getInstance();
prefs.remove('counter'); // 데이터 삭제

모든 데이터 삭제는 prefs.clear();

 

 

예제

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
 
class SharedPreferencesDemo extends StatefulWidget {
  const SharedPreferencesDemo({Key? key}) : super(key: key);
 
  @override
  State<SharedPreferencesDemo> createState() => _SharedPreferencesDemoState();
}
 
class _SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
  // Future 은 미래의 값을 의미한다.
  // Future는 비동기 작업의 결과를 나타내며
  // 미완료(value를 생성하기 전)또는 완료(value 생성)의 두 가지 상태를 가질 수 있다.
  // Dart에서는 비동기 작업을 수행하기 위해 Future클래스와 async 및 await 키워드를 사용할 수 있다.
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  late Future<int> _counter;
 
  // async : 함수 본문 앞에 키워드로 사용하여 비동기로 표시
  // Future는 Future<타입명> 이런식으로 타입을 명시해야 한다.
  Future<void> _incrementCounter() async {
    final SharedPreferences prefs = await _prefs;
    final int counter = (prefs.getInt('counter') ?? 0+ 1;
 
    setState(() {
      _counter = prefs.setInt('counter', counter).then((bool success) {
        return counter;
      });
    });
  }
 
  @override
  void initState() {
    super.initState();
    _counter = _prefs.then((SharedPreferences prefs) {
      return prefs.getInt('counter') ?? 0;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SharedPreferences Demo'),
      ),
      body: Center(
          child: FutureBuilder<int>(
              future: _counter,
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return const CircularProgressIndicator();
                  default:
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    } else {
                      return Text(
                        '${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n'
                       'This should persist across restarts.',
                      );
                    }
                }
              })),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

 

728x90
블로그 이미지

Link2Me

,