DevBoi

[Flutter] shared_preferences 사용 본문

[Mobile]/[Flutter]

[Flutter] shared_preferences 사용

HiSmith 2023. 7. 23. 22:37
반응형

1. 의존성 추가

shared_preferences: ^2.2.0

 

2. 텍스트 받을 위젯 세팅

final _contentEditController = TextEditingController();

child: TextField(
                controller: _contentEditController,
                style: TextStyle(color: Colors.black),
                decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: '메모를 입력해주세요',
                    hintStyle: TextStyle(color: Colors.grey[300])),
                cursorColor: Colors.blue,
              ),

 

3. 인스턴스 초기화 (대부분 State단에서 선언)

final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

 

4. 저장 및 조회 

_prefs.setInt('counter',1);
_prefs.getInt('counter')

 

5.동적 할당 및 리스트 저장 및 조회 사용

별도의 메모 객체 생성

save(String text) async{
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  final SharedPreferences prefs = await _prefs;
  //일단 데이터 다 가져오기
  String? memos= await prefs.getString("smithMemo");
  //처음일때
  if(memos == null){
    Memo memo = new Memo(0,text,"N");
    List<Memo> list = <Memo>[memo];
    prefs.setString("smithMemo", jsonEncode(list));
  }
  //추가할떄
  else{
    var jsonData = json.decode(memos!);
    List <Memo> list = List<Memo>.from(jsonData.map((x) => Memo.fromJson(x)));
    Memo memo = new Memo(list.length,text,"N");
    list.add(memo);
    prefs.setString("smithMemo", jsonEncode(list));
  }
  print(prefs.getString("smithMemo"));
}

 

조금 짤라서 보면 이렇다.

 

메모 리스트를 json decode 로 변환하여, 리스트로 리턴한다.

var jsonData = json.decode(memos!);
List <Memo> list = List<Memo>.from(jsonData.map((x) => Memo.fromJson(x)));

 

메모 클래스

class Memo{
  int? id;
  String? content;
  String? completeYn;

  Memo(int id,String content,String completeYn){
    this.id = id;
    this.content = content;
    this.completeYn = completeYn;
  }


  Map<String, dynamic> toJson() {
    return {
      'id': this.id,
      'content': this.content,
      'completeYn': this.completeYn,
    };
  }

  factory Memo.fromJson(Map<String, dynamic> json) {
    return Memo(json['id'],json['content'],json['completeYn']);

  }
}

 

결국은 커스텀 객체도 그냥 String 으로 데이터를 넣고 입출력하는 것의 반복일 뿐이다.

해당 관련 전체 소스이다.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:memosmith/MemoInterface.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:memosmith/memo.dart';



late SharedPreferences prefs;
List<Memo> list = <Memo>[];
final String prefix= "smithMemo";

void main() {

  runApp(const MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),

    );
  }
}

class MyHomePage extends StatefulWidget {

  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


  @override
  void initState() {
    settingList();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    print(list);
    return Scaffold(
      backgroundColor: Colors.blue,
      body: ListView.builder(
        itemCount: list.length,
        itemBuilder: (BuildContext context,int index){
        return Text(list[index].content as String);
      }),


      floatingActionButton: FloatingActionButton(
        onPressed: () => _dialogBuilder(context),
        tooltip: 'Increment',
        backgroundColor: Colors.white,
        child: const Icon(Icons.add,color: Colors.black,),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Future<void> _dialogBuilder(BuildContext context) {
  final _contentEditController = TextEditingController();
  return showDialog<void>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('메모 추가'),
        content: Row(children: <Widget>[

          Flexible(
            child: Container(
              margin: EdgeInsets.only(right: 20),
              child: TextField(
                controller: _contentEditController,
                style: TextStyle(color: Colors.black),
                decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: '메모를 입력해주세요',
                    hintStyle: TextStyle(color: Colors.grey[300])),
                cursorColor: Colors.blue,
              ),
            ),
          ),
        ]),
        actions: <Widget>[
          TextButton(
            style: TextButton.styleFrom(
              textStyle: Theme
                  .of(context)
                  .textTheme
                  .labelLarge,
            ),
            child: const Text('취소'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          TextButton(
            style: TextButton.styleFrom(
              textStyle: Theme
                  .of(context)
                  .textTheme
                  .labelLarge,
            ),
            child: const Text('저장'),
            onPressed: () {
              save(_contentEditController.text);
              list.add(new Memo(list.length,_contentEditController.text,"N"));
            },
          ),
        ],
      );
    },
  );
}



save(String text) async{
  prefs = await  SharedPreferences.getInstance();
  //일단 데이터 다 가져오기
  var memos= await prefs.getString(prefix);
  //처음일때
  if(memos == null){
    Memo memo = new Memo(0,text,"N");
    List<Memo> list = <Memo>[memo];
    prefs.setString(prefix, jsonEncode(list));
  }
  //추가할떄
  else{
    var jsonData = json.decode(memos!);
    List <Memo> list = List<Memo>.from(jsonData.map((x) => Memo.fromJson(x)));
    Memo memo = new Memo(list.length,text,"N");
    list.add(memo);
    prefs.setString(prefix, jsonEncode(list));
  }

}

settingList() async{
  print('start');
  prefs = await  SharedPreferences.getInstance();
  var memoList = prefs.getString(prefix);
  var jsonData = json.decode(memoList!);
  list =  List<Memo>.from(jsonData.map((x) => Memo.fromJson(x)));
}

 

 

리스트뷰에 저장한 전체 데이터를 넣는다.

반응형