[flutter] shared_preferences 를 사용하여 사용자가 선택한 폰트 크기를 저장하는 방법은 무엇인가요?

Flutter에서는 사용자가 선택한 폰트 크기를 저장하고 다음에 앱이 실행될 때 해당 폰트 크기를 복원하는 기능을 구현할 수 있습니다. 이를 위해 shared_preferences 패키지를 사용할 수 있습니다.

shared_preferences 패키지 추가하기

먼저, shared_preferences 패키지를 프로젝트에 추가해야 합니다. pubspec.yaml 파일을 열고 dependencies 섹션에 다음 라인을 추가합니다:

dependencies:
  shared_preferences: ^2.0.7

그리고 터미널에서 flutter pub get 명령을 실행하여 패키지를 다운로드합니다.

폰트 크기 저장하기

아래 예제 코드는 사용자가 폰트 크기를 선택할 수 있는 Slider 위젯을 포함한 화면을 구현한 예시입니다:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class FontSizePage extends StatefulWidget {
  @override
  _FontSizePageState createState() => _FontSizePageState();
}

class _FontSizePageState extends State<FontSizePage> {
  double _fontSize = 16.0; // 기본 폰트 크기

  @override
  void initState() {
    super.initState();
    _loadFontSize(); // 앱 실행시 폰트 크기 불러오기
  }

  void _loadFontSize() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    double fontSize = prefs.getDouble('font_size');
    if (fontSize != null) {
      setState(() {
        _fontSize = fontSize;
      });
    }
  }

  void _saveFontSize(double fontSize) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble('font_size', fontSize);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('폰트 크기 설정'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              '폰트 크기',
              style: TextStyle(fontSize: _fontSize),
            ),
            Slider(
              value: _fontSize,
              min: 10.0,
              max: 30.0,
              onChanged: (newValue) {
                setState(() {
                  _fontSize = newValue;
                });
              },
              onChangeEnd: _saveFontSize,
            ),
          ],
        ),
      ),
    );
  }
}

위 코드에서 SharedPreferences를 사용하여 폰트 크기를 저장하고 불러오는 기능을 구현하였습니다. _loadFontSize 함수는 앱이 실행될 때 저장된 폰트 크기를 불러와서 _fontSize 변수에 저장하고, _saveFontSize 함수는 사용자가 폰트 크기를 선택한 후에 해당 폰트 크기를 저장합니다.

설정한 폰트 크기 복원하기

폰트 크기를 저장하는 기능을 구현했다면, 앱이 다음에 실행될 때 저장된 폰트 크기를 복원하는 기능을 추가할 수 있습니다. 예를 들어, 앱의 main 함수에서 처음 실행되는 화면인 HomePage 위젯을 FontSizePage 위젯으로 변경하여 폰트 크기를 설정하도록 할 수 있습니다:

import 'package:flutter/material.dart';

import 'font_size_page.dart'; // FontSizePage를 import 해주어야 합니다

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 폰트 크기 저장',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FontSizePage(), // FontSizePage로 변경합니다
    );
  }
}

이렇게 수정하면 앱이 실행될 때 저장된 폰트 크기를 복원하고, 사용자가 폰트 크기를 선택할 수 있게 됩니다.

결론

Flutter에서는 shared_preferences 패키지를 사용하여 사용자가 선택한 폰트 크기를 저장하고 복원할 수 있습니다. 위 예제를 참고하여 앱에 폰트 크기 설정 기능을 추가해보세요.

더 자세한 정보는 shared_preferences 패키지 문서를 확인하세요.