Notice
Recent Posts
Recent Comments
Link
민스씨의 일취일장
Flutter | shared_preference 간단 사용 방법 본문
반응형
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
반응형
'Mobile > Flutter & Dart' 카테고리의 다른 글
Flutter | MaterialApp title vs. AppBar title - title이 두개인 이유 (0) | 2024.12.30 |
---|---|
Flutter | FlatButton 없어지고 새로운 material button 사용해야 한다 (0) | 2024.12.26 |
TIssue | Flutter | Text 위젯에서 textAlign 속성지정으로 가운데 정렬이 되지 않는 이유 (0) | 2024.12.26 |
TIssue | Android Studio | Flutter | 시뮬레이터 DEBUG 빨강 리본 제거하기 (0) | 2024.12.24 |
TIssue | Flutter | primaryColor 설정해도 AppBar 색상이 흰색인 이유 (0) | 2024.12.20 |