커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
3주차 숙제
앱개발 종합반 - 플러터 v8
3주차
북마크
김*윤
댓글
7
추천
0
조회수
17
조회수
17
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


content: json['content'] 는 뒤에 ??를 안붙였는데 isPinned는 굳이 isPinned: json['isPinned'] ?? false를 붙인 이유를 알고 싶습니다.







import 'dart:convert';


import 'package:flutter/material.dart';


import 'main.dart';


// Memo 데이터의 형식을 정해줍니다. 추후 isPinned, updatedAt 등의 정보도 저장할 수 있습니다.
class Memo {
  Memo({
    required this.content,
    this.isPinned = false,
  });


  String content;
  bool isPinned;


  Map toJson() {
    return {
      'content': content,
      'isPinned': isPinned,
    };
  }


  factory Memo.fromJson(json) {
    return Memo(
      content: json['content'],
      isPinned: json['isPinned'] ?? false,
    );
  }
}


// Memo 데이터는 모두 여기서 관리
class MemoService extends ChangeNotifier {
  MemoService() {
    loadMemoList();
  }


  List<Memo> memoList = [
    Memo(content: '장보기 목록: 사과, 양파'), // 더미(dummy) 데이터
    Memo(content: '새 메모'), // 더미(dummy) 데이터
  ];


  createMemo({required String content}) {
    Memo memo = Memo(content: content);
    memoList.add(memo);
    notifyListeners(); // Consumer<MemoService>의 builder 부분을 호출해서 화면 새로고침
    saveMemoList();
  }


  updateMemo({required int index, required String content}) {
    Memo memo = memoList[index];
    memo.content = content;
    notifyListeners();
    saveMemoList();
  }


  updatePinMemo({required int index}) {
    Memo memo = memoList[index];
    memo.isPinned = !memo.isPinned;
    memoList = [
      ...memoList.where((element) => element.isPinned),
      ...memoList.where((element) => !element.isPinned)
    ];
    notifyListeners();
    saveMemoList();
  }


  deleteMemo({required int index}) {
    memoList.removeAt(index);
    notifyListeners();
    saveMemoList();
  }


  saveMemoList() {
    List memoJsonList = memoList.map((memo) => memo.toJson()).toList();
    // [{"content": "1"}, {"content": "2"}]


    String jsonString = jsonEncode(memoJsonList);
    // '[{"content": "1"}, {"content": "2"}]'


    prefs.setString('memoList', jsonString);
  }


  loadMemoList() {
    String? jsonString = prefs.getString('memoList');
    // '[{"content": "1"}, {"content": "2"}]'


    if (jsonString == null) return; // null 이면 로드하지 않음


    List memoJsonList = jsonDecode(jsonString);
    // [{"content": "1"}, {"content": "2"}]


    memoList = memoJsonList.map((json) => Memo.fromJson(json)).toList();
  }
}


취소
 공유
취소
댓글 0
댓글 알림
나의얼굴