728x90

앱 내에 key-value 형태로 데이터를 저장하려면 shared preferences 라이브러리를 이용한다.

자동 로그인 처리 쉽게 하려고 패스워드 정보 저장하면 안된다.

 

1. 의존성 추가

pubspec.yaml 파일에 shared_preferences 라이브러리를 추가한다.

터미널 창에서 flutter pub add shared_preferences 한 다음에 flutter pub get 을 하면 자동으로 최신 버전이 추가된다.

https://pub.dev/packages/shared_preferences/install 

 

2. 데이터 저장하기

void _saveCookie(String newCookie) async {
  if (_cookie != newCookie) {
    _cookie = newCookie;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('cookie', _cookie!);
  }
}

Shared preferences에는 int, double, bool, string, 그리고 List<String> 데이터를 저장할 수 있다.

 

3. 데이터 읽기

Future<void> initCookie() async {
  // shared preferences 얻기
  SharedPreferences prefs = await SharedPreferences.getInstance();
  _cookie = prefs.getString('cookie');
}
 

 

 

 

4. 데이터 삭제하기

void _clearCookie() async {
  _cookie = null;
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.remove('cookie');
}

모든 데이터 삭제는 prefs.clear(); 를 하면 된다.

 

 

블로그 이미지

Link2Me

,