[Flutter/Riverpod] FutureProvider로 체크리스트 구현하기

찌니·2023년 3월 24일
0

Flutter

목록 보기
7/13

사실 본인도 Riverpod을 공부하기 시작한지 얼마 되지 않았다. 약 1개월????
Provider를 사용하던 본인은 Provider의 업그레이드라는 Riverpod을 보며 이게 맞나?? 전혀 비슷한 점이 없잖아!! 너무 어렵잖아!!! 👿
라고 생각했지만 한달이 지난 지금은 Provider의 업그레이드 버전이라는 점을 인정한다...

이런 카와이한 체크리스트를 구현할 예정이다!

본인이 벨로그를 볼때 불편했던 점이 글로 보면 코드가 눈에 안들어오는데 사진은 복사는 해야할 때 불편한 점이 있어서 사진과 코드 둘 다 올리겠읍니다 코드가 필요하신 분은 아래에 가면 보실 수 있습니당

CheckListModel

CheckListService

서버에서 checklist model의 list를 받아와서 출력하는 service의 코드이다
참고로 본인은 Dio를 사용하며 Dio가 좋다
DioClient 코드는 아래에 참고용으로 올릴 예정이지만 이 부분을 깔끔하게 만드는 방법을 고안중이기 때문에 굳이 보고싶다면 참고로만 보는것을 추천한다

CheckListWidget && FutureProvider

너무 길어서 사진 잘린 점 양해 부탁


FutureProvider의 가장 좋아하는 점이다!!!!!! when()!!!
정말 간단하게 상태관리를 할 수 있다. 절대 widget단의 예외상황이 발생하지 않는다

이렇게 FutureProvider를 이용한 체크리스트 마무리 하겠읍니다 씨야~~~

!참고용 DioClient

(아래는 복붙용 코드..물론 필요한 분만)

CheckListModel

enum CheckListState { BEFORE, ING, SUCCESS, FAILL }

class CheckList {
 int checkListId;
 int patientId;
 String startDate;
 String endDate;
 String content;
 CheckListState state;

 CheckList(
     {required this.checkListId,
     required this.patientId,
     required this.startDate,
     required this.endDate,
     required this.content,
     required this.state});

 factory CheckList.fromJson(Map<String, dynamic> json) {
   return CheckList(
       checkListId: json['checklist_id'],
       patientId: json['patient_id'],
       startDate: json['start_date'],
       endDate: json['end_date'],
       content: json['content'],
       state: CheckListState.values[json['state']]);
 }
}

CheckListService

class ChecklistService {
  final String? _baseUrl = dotenv.env['BASE_URL'];

  Future<List<CheckList>> getChecklists() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final int id = prefs.getInt('id')!;

    final response = await DioClient()
        .get('$_baseUrl/checklist/get/today/$id', {'patient_id': id}, true);
    if (response.result == Result.success) {
      List<CheckList> checklist = response.response
          .map((counselor) {
            return CheckList.fromJson(counselor);
          })
          .cast<CheckList>()
          .toList();
      return checklist;
    } else {
      throw Exception('Failed to load checklists from API');
    }
  }
}

CheckListWidget & FutureProvider


final checkListProvider = FutureProvider.autoDispose<List<CheckList>>(
    (ref) => ChecklistService().getChecklists());
    
    
class CheckListWidget extends ConsumerWidget {
  const CheckListWidget({super.key});

  
  Widget build(BuildContext context, WidgetRef ref) {
    final checkList = ref.watch(checkListProvider);
    return Container(
        padding: const EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          color: Colors.white38,
          borderRadius: BorderRadius.circular(20),
        ),
        width: double.infinity,
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: checkList.when(
                data: ((data) {
                  if (data.isEmpty) {
                    return [
                      Container(
                        padding: const EdgeInsets.only(left: 15),
                        child: const Text(
                          'no checkList in today',
                          style: TextStyle(
                              fontSize: 18,
                              color: Colors.white,
                              height: 1.4,
                              fontWeight: FontWeight.w600),
                        ),
                      )
                    ];
                  } else {
                    return data
                        .map(
                          (e) => Row(
                            children: [
                              Checkbox(
                                fillColor:
                                    MaterialStateProperty.all(Palette.appColor),
                                value: false,
                                onChanged: (value) {
                                  if (value!) {
                                    e.state = CheckListState.SUCCESS;
                                  } else {
                                    e.state = CheckListState.FAILL;
                                  }
                                },
                              ),
                              Text(
                                e.content,
                                style: const TextStyle(
                                    fontSize: 18,
                                    color: Colors.black87,
                                    height: 1.4,
                                    fontWeight: FontWeight.w600),
                              ),
                            ],
                          ),
                        )
                        .toList();
                  }
                }),
                loading: () => [const Text('Loading...')],
                error: (error, stackTrace) => [
                      const Text(
                        'fail to load checkList',
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.black87,
                            height: 1.4,
                            fontWeight: FontWeight.w600),
                      ),
                    ])));
  }
}
profile
찌니's develog

0개의 댓글