[flutter] shared_preferences 를 사용하여 사용자가 참여한 스터디 목록을 저장하는 방법은 무엇인가요?

Flutter 앱에서 사용자가 참여한 스터디 목록을 로컬에 저장하려면 shared_preferences 패키지를 사용할 수 있습니다. 이 패키지는 간단하게 키-값 쌍을 저장하여 사용자 데이터를 유지할 수 있도록 도와줍니다.

1. shared_preferences 패키지 추가하기

먼저, shared_preferences 패키지를 추가해야 합니다. pubspec.yaml 파일을 열고, 다음과 같이 패키지를 추가해주세요:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.0.6

패키지를 추가한 후에는 flutter pub get 명령어를 실행하여 패키지를 가져옵니다.

2. 스터디 목록 저장하기

이제 shared_preferences 패키지를 사용하여 사용자의 참여한 스터디 목록을 저장해보겠습니다.

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

class StudyListPage extends StatefulWidget {
  @override
  _StudyListPageState createState() => _StudyListPageState();
}

class _StudyListPageState extends State<StudyListPage> {
  List<String> studies = [];

  @override
  void initState() {
    super.initState();
    loadStudies();
  }

  Future<void> loadStudies() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      studies = prefs.getStringList('studies') ?? [];
    });
  }

  Future<void> saveStudies() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('studies', studies);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Study List'),
      ),
      body: ListView.builder(
        itemCount: studies.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(studies[index]),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              String newStudy = '';
              return AlertDialog(
                title: Text('Add Study'),
                content: TextFormField(
                  onChanged: (value) {
                    newStudy = value;
                  },
                ),
                actions: [
                  FlatButton(
                    child: Text('Cancel'),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                  FlatButton(
                    child: Text('Save'),
                    onPressed: () {
                      setState(() {
                        studies.add(newStudy);
                        saveStudies();
                        Navigator.pop(context);
                      });
                    },
                  ),
                ],
              );
            },
          );
        },
      ),
    );
  }
}

위 코드에서 StudyListPage 위젯은 사용자가 참여한 스터디 목록을 보여주고, 새로운 스터디를 추가할 수 있는 화면을 구성합니다.

loadStudies 함수는 SharedPreferences에서 저장된 스터디 목록을 불러와서 studies 리스트에 저장합니다.

saveStudies 함수는 studies 리스트를 SharedPreferences에 저장합니다.

FloatingActionButton을 누르면 showDialog 함수를 통해 새로운 스터디를 추가할 수 있는 다이얼로그가 뜹니다. 사용자가 스터디 이름을 입력하고 ‘Save’ 버튼을 누르면, studies 리스트에 스터디가 추가되고 saveStudies 함수를 호출하여 변경된 목록이 SharedPreferences에 저장됩니다.

위 코드는 기본적인 사용자 데이터 저장 및 불러오기 프로세스를 보여줍니다. 해당 코드를 알맞게 활용하여 직접 앱에 적용해보세요.

참고 자료