- [flutter]sharedPreference 사용 실수 목차
Future<void> _saveLotto(number) async {
prefs = await SharedPreferences.getInstance();
String save = json.encode(number);
print(save);
prefs.setString('lotto', save);
}
Future<List<int>> loadLotto() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
print(prefs);
var number = json.decode(prefs.getString('lotto'));
print(number);
return (number);
}
이렇게 선언을 하고 _saveLotto()를 실행한 후에 loadLotto()를 실행해도 계속 null이 나왔다
그래서 SharedPreference의 인스턴스를 각 함수에서 불러옴으로 별도의 인스턴스를 부르는 것으로
생각을 하여 수정을 하였다
SharedPreferences prefs; <- 전역변수로 선언을 하고
Future<void> _saveLotto(number) async {
prefs = await SharedPreferences.getInstance();
String save = json.encode(number);
print(save);
prefs.setString('lotto', save);
}
Future<List<int>> loadLotto() async {
//SharedPreferences prefs = await SharedPreferences.getInstance(); <- 인스턴스 불러 오는 것을 주석처리하고
var number = json.decode(prefs.getString('lotto')); <- 전역변수로 선언된 prefs 인스턴스를 사용하였다
print(number);
return (number);
}
결과는 예상에 맞게 잘 수행되었다
참고로 나는 List<int>를 저장한다
그러나 SharedPreference에는 List<int>를 저장하는 것이 없어서 json타입으로 encode를 하였다
가져올는 경우에는 물론 decode해야 한다
즐거운 시간되세요^^
'flutter' 카테고리의 다른 글
[flutter]Too many positional arguments: 0 allowed, but 1 found. (0) | 2021.01.30 |
---|---|
[flutter]List<dynamic>' is not a subtype of type 'FutureOr<List<int>> (0) | 2021.01.10 |
[flutter]print() (0) | 2020.12.27 |
[flutter]The instance member '_number' can't be accessed in an initializer. (0) | 2020.12.26 |
[flutter]'await' applied to 'String', which is not a 'Future' (0) | 2020.12.26 |