Flutter 개발일지 day 11

listview 도입

1
2
3
4
5
6
7
8
9
10
ListView.builder(
    itemCount: 1, //임시 element 개수
    itemBuilder: (BuildContext context, int idx){
      return Container(
        height: 25,
        color: Pastel.green,
        child: Text("test $idx"), // hive로 box.get(일자)[idx]
      );
    }
)

그리고 임시로 껍데기뿐인 listview를 도입했다. scaffold(=화면) 윗부분은 일들로 이루어진 container들로 가득 차 있고, 그 아래에 Appbar로 “to-do”를 띄우고 그 아래부터 listview로 우리가 hivebox에 저장해준 “그 날짜의 scheduleClass의 list”를 띄워준다. 일단은 임시로 넣었기에 hivebox에서 가져오지도 않고 길이도 1로 고정되어있다. 나중에 list에 따라 listview의 길이와 content가 바뀌도록 할 것이다.

type error 해결

분명 저번시간에는 아무런 문제가 없었는데, 이번에 실행해보니 자꾸 sub type에러가 떴다. “ScheduleClass에 dynamic을 할당할 수 없다”고 한다…

1
2
3
4
5
6
7
8
9
/*** main.dart ***/
//await Hive.openBox<List<ScheduleClass>>('lib') //cause type error
await Hive.openBox<List>('lib');

/*** monthCal.dart ***/
//valueListenable: Hive.box<List<ScheduleClass>>('lib').listenable(),
//builder: (context, Box<List<ScheduleClass>> box, child) {return (...)} // cause type error
valueListenable: Hive.box<List>('lib').listenable(),
builder: (context, Box<List> box, child) {return (...)}

당연히 FloatingActionButton을 통해서 할당하는 값이 분명히 ScheduleClass가 되도록 확인을 했음에도 불구하고 계속 오류가 떠서 진짜 막막했다. 그래서 그냥 특정한 타입을 지정하는 것을 포기했다! List<ScheduleClass>라고 쓰는걸 포기하고 그냥 List로 쓰는식으로 말이다. 당연히 dynamic에는 모든 type이 할당될 수 있으므로 문제 해결.

FloatingActionButton 수정

정확히는 FloatingActionButton의 onpressed를 수정했다고 해야겠다. 기존의 코드를 보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//monthCal.dart
FloatingActionButton(
  onPressed: () async{
    box.clear();
    int i = 0;
    if(!box.containsKey('2022.12.25')) {
      box.put("2022.12.25", []);
      box.get("2022.12.25")!.add(ScheduleClass(name: "t$i", date: DateTime.now()));
    }
    else{
      box.get("2022.12.25")!.add(ScheduleClass(name: "t$i", date: DateTime.now()));
    }
    i++;
    print(box.get("2022.12.25"));
  },
),

여기서 일정을 새로 추가하는 방식으로 보면 read 해온 값에다가 add한다. 즉 아무런 의미 없는 행위를 한 것이다. box.get을 해온 값에 무언가 operation을 주어봤자 원본을 참조하지 않는 이상은 원본은 바뀌지 않는다. 그래서 이를 요렇게 바꿨다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
FloatingActionButton(
  onPressed: () async{
    int i = 0;
    if(box.containsKey('2022.12.25')) {
      List tmp = box.get("2022.12.25")!;
      tmp.add(ScheduleClass(name: "t$i", date: DateTime.now()));
      box.put("2022.12.25", tmp);
    }
    else {
      List tmp = [ScheduleClass(name: "t$i", date: DateTime.now())];
      box.put("2022.12.25", tmp);
    }
    i++;
    print("will print get");
    print(box.get("2022.12.25"));
  },
),

먼저 box.get으로 가져온 값을 임시 list인 tmp에 할당해 준다. 그래서 그 tmp에 add와 같은 operation을 해주고, 모든 조작이 끝난 tmp를 box.put을 통해 box에 직접 write해준다. 이렇게 하면 문제 해결!

배운점

  1. 아직도 왜 type error가 떴는지는 잘 모르겠지만, 괜히 오류 잡겠다고 시간을 너무 오래 쓴 것 같다. 그냥 dynamic으로 해버렸으면 편했을텐데…
  2. box.get에 값을 할당해버렸던 오류… 앞으로 database에서 read & write을 할 일이 많을텐데 이런 실수 또 하지 않게 주의해야겠다.