Mobile/Flutter & Dart
Flutter | shared_preference 간단 사용 방법
읻민스
2025. 2. 11. 12:32
반응형
shared_preference 사용방법에 대한 글이다.
Flutter - shared_preference 사용 방법
shared_preferences란?
shared_preferences는 Android와 iOS의 네이티브 저장소를 사용하기 위해 사용하는 플러그인이다. 네이티브 저장소를 사용할 때, Android는 SharedPreferences API를, iOS는 NSUserDefaults를 사용한다. Flutter에서 shared_preferences는 이 둘을 감싸고 있어 하나의 코드로 함께 다룰 수 있도록 도와준다.
사용방법
1️⃣ 패키지 설치하기
pubspec.yaml에 패키지를 추가해준다.
dependencies:
shared_preferences: latest_version
추가(설치) 후 flutter pub get은 필수이다.
⚠️ $flutter pub get
2️⃣ 사용방법
- 패키지 import 하기
import 'package:shared_preferences/shared_preferences.dart';
사용은 4가지 만 알아두면 된다. 인스턴스 불러오기, 저장하기, 불러오기, 삭제하기이다.
- 인스턴스 불러오기
prefs = await SharedPreferences.getInstance();
- 데이터 저장하기
await prefs.setString('name', 'ydmins');
await prefs.setInt('age', 3);
- 데이터 불러오기
prefs.getString('name');
prefs.getInt('age');
- 데이터 삭제하기
await prefs.remove('name');
await prefs.remove('age');
특징
- shared_preferences는 비동기적(async/await)으로 작동한다.
- 싱글톤 객체이기 때문에, 앱의 어떤 곳에서도 같은 컨텍스트로 사용이 가능하다.
- 앱이 삭제되면 데이터도 함께 삭제된다.
- 보안에 취약하다. (민감한 데이터의 경우 flutter_secure_storage를 사용해야 한다.)
728x90
반응형