[flutter] shared_preferences를 활용하여 사용자의 폰트 크기 설정을 수정하는 방법은?
안녕하세요! Flutter 앱에서 사용자의 폰트 크기 설정을 수정하는 방법에 대해 알아보겠습니다.
1. shared_preferences
패키지 설치
먼저, 폰트 크기를 저장하고 관리하기 위해 shared_preferences
패키지를 설치합니다.
flutter pub add shared_preferences
2. 폰트 크기 설정 및 저장
사용자가 선택한 폰트 크기를 설정하고 shared_preferences
를 사용하여 이를 저장합니다.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class FontSizeSettingScreen extends StatefulWidget {
@override
_FontSizeSettingScreenState createState() => _FontSizeSettingScreenState();
}
class _FontSizeSettingScreenState extends State<FontSizeSettingScreen> {
double _fontSize = 16.0;
static const _keyFontSize = 'font_size';
@override
void initState() {
super.initState();
_loadFontSize();
}
_loadFontSize() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
double fontSize = prefs.getDouble(_keyFontSize) ?? 16.0;
setState(() {
_fontSize = fontSize;
});
}
_saveFontSize(double fontSize) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setDouble(_keyFontSize, fontSize);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('폰트 크기 설정'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Slider(
value: _fontSize,
min: 10,
max: 30,
onChanged: (val) {
setState(() {
_fontSize = val;
_saveFontSize(val);
});
},
),
Text(
'선택한 폰트 크기: ${_fontSize.toStringAsFixed(1)}',
style: TextStyle(fontSize: _fontSize),
),
],
),
),
);
}
}
위의 코드는 폰트 크기를 슬라이더로 선택하여 설정하고, shared_preferences
를 사용하여 설정값을 저장하는 화면을 구현한 예시입니다.
이제 사용자는 앱을 다시 시작해도 이전에 선택한 폰트 크기 설정이 유지됩니다.
결론
shared_preferences
를 이용하여 사용자의 폰트 크기 설정을 저장하고, 필요할 때 불러와서 적용하는 방법을 살펴보았습니다. 이를 통해 사용자 경험을 향상시키고 더 편리한 앱을 제작할 수 있습니다.
더 많은 정보를 원하시면 shared_preferences 패키지 문서를 참고해보세요.