인프런 커뮤니티 질문&답변

karismafish님의 프로필 이미지
karismafish

작성한 질문수

[2024 최신] [코드팩토리] [초급] Flutter 3.0 앱 개발 - 10개의 프로젝트로 오늘 초보 탈출!

캘리더 강의중에서 시차 관련 부분 강의에서요

작성

·

370

0

List<Schedule> schedules = []; if(snapshot.hasData){ schedules = snapshot.data!.where((element) => element.date == selectedDate).toList(); } 이 부분에서

Try correcting the name to the name of an existing getter, or defining a getter or field named 'selectedDate'.

이런 오류메세지가 나옵니다 ㅠㅠ

 

답변 2

0

안녕하세요 ! 저도 동일한 이슈가 있는데요!

Screen Shot 2023-02-24 at 2.38.56 PM.png

home_screen.dart

import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:schedule/component/schedule_bottom_sheet.dart';
import 'package:schedule/component/schedule_card.dart';
import 'package:schedule/component/today_banner.dart';
import 'package:schedule/const/colors.dart';
import 'package:schedule/component/calender.dart';

import '../component/calender.dart';
import '../database/drift_database.dart';


class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  DateTime selectedDay = DateTime(
    DateTime
        .now()
        .year,
    DateTime
        .now()
        .month,
    DateTime
        .now()
        .day,
  );
  DateTime focusedDay = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: renderFloatingActionButton(),
      body: SafeArea(
        child: Column(
          children: [
            Calendar(
              selectedDay: selectedDay,
              focusedDay: focusedDay,
              onDaySelected: onDaySelected,
            ),
            SizedBox(height: 8.0),
            TodayBanner(
              selectedDay: selectedDay,
              scheduleCount: 3,
            ),
            SizedBox(height: 8.0),
            _ScheduleList(),
          ],
        ),
      ),
    );
  }

  FloatingActionButton renderFloatingActionButton() {
    return FloatingActionButton(
        onPressed: () {
          showModalBottomSheet(
            context: context,
            isScrollControlled: true,
            builder: (_){
              return ScheduleBottomSheet(
                selectedDate: selectedDay,
              );
          },

          );

        },
        backgroundColor: PRIMARY_COLOR,
        child: Icon(
          Icons.add,
        ));
  }

  onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    setState(() {
      this.selectedDay = selectedDay;
      this.focusedDay = selectedDay;
    });
  }
}

class _ScheduleList extends StatelessWidget {
  const _ScheduleList({Key? key}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0),
          child: StreamBuilder<List<Schedule>>(
            stream: GetIt.I<LocalDatabase>().watchSchedules(),
            builder: (context, snapshot) {

              List<Schedule> schedules = [];

              if(snapshot.hasData){
                schedules = snapshot.data!.where((element) => element.date == selectedDate).toList();
              }






              return ListView.separated(
                  itemCount: 3,
                  separatorBuilder: (context, index) {
                    return SizedBox(
                      height: 8.0,
                    );
                  },
                  itemBuilder: (context,
                      index,) {
                    return ScheduleCard(
                      startTime: 8,
                      endTime: 9,
                      content: '프로그래밍, $index',
                      color: Colors.red,
                    );
                  });
            }
          )),
    );
  }
}

 

schedule_bottom_sheet.dart

import 'package:drift/drift.dart' show Value;
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:schedule/component/custom_text_field.dart';
import 'package:schedule/const/colors.dart';
import 'package:schedule/database/drift_database.dart';
import 'package:schedule/model/category_color.dart';
import 'package:schedule/screen/home_screen.dart';

class ScheduleBottomSheet extends StatefulWidget {
  final DateTime selectedDate;

  const ScheduleBottomSheet({
    required this.selectedDate,
    Key? key,
  }) : super(key: key);

  @override
  State<ScheduleBottomSheet> createState() => _ScheduleBottomSheetState();
}

class _ScheduleBottomSheetState extends State<ScheduleBottomSheet> {
  final GlobalKey<FormState> formKey = GlobalKey();
  int? startTime;
  int? endTime;
  String? content;
  int? selectedColorId;

  @override
  Widget build(BuildContext context) {
    final bottomInset = MediaQuery.of(context).viewInsets.bottom;

    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: SafeArea(
        child: Container(
          color: Colors.white,
          height: MediaQuery.of(context).size.height / 2 + bottomInset,
          child: Padding(
            padding: EdgeInsets.only(bottom: bottomInset),
            child: Padding(
              padding: EdgeInsets.only(left: 8.0, right: 8.0, top: 16.0),
              child: Form(
                key: formKey,

                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _Time(
                      onStartSaved: (String? val) {
                        startTime = int.parse(val!);
                      },
                      onEndSaved: (String? val) {
                        endTime = int.parse(val!);
                      },
                    ),
                    SizedBox(
                      height: 16.0,
                    ),
                    _Content(
                      onSaved: (String? val) {
                        content = val;
                      },
                    ),
                    SizedBox(
                      height: 16.0,
                    ),
                    FutureBuilder<List<CategoryColor>>(
                        future: GetIt.I<LocalDatabase>().getCategoryColors(),
                        builder: (context, snapshot) {
                          if (snapshot.hasData &&
                              selectedColorId == null &&
                              snapshot.data!.isNotEmpty) {
                            selectedColorId = snapshot.data![0].id;
                          }

                          return _ColorPicker(
                              colors: snapshot.hasData ? snapshot.data! : [],
                              selectedColorId: selectedColorId,
                              colorIdSetter: (int id) {
                                setState(() {
                                  selectedColorId = id;
                                });
                              });
                        }),
                    SizedBox(
                      height: 8.0,
                    ),
                    _SaveButton(
                      onpressed: onSavePressed,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  void onSavePressed() async{
    // formKey는 생성을 했을때
    // Form 위젯과 결합을 안했을때
    if (formKey.currentState == null) {
      return;
    }
    if (formKey.currentState!.validate()) {
      print('에러가 없습니다.');
      formKey.currentState!.save();
      print('$startTime');
      print('$endTime');
      print('$content');

      final key = await GetIt.I<LocalDatabase>().createSchedule(
        SchedulesCompanion(
          date : Value(widget.selectedDate),
          startTime : Value(startTime!),
          endTime: Value(endTime!),
          content: Value(content!),
          colorId: Value(selectedColorId!),

        )
      );
      print( 'save complete $key');
      Navigator.of(context).pop();
    } else {
      print('에러가 있습니다..');
    }
  }
}

class _Time extends StatelessWidget {
  final FormFieldSetter<String> onStartSaved;
  final FormFieldSetter<String> onEndSaved;

  const _Time({
    required this.onStartSaved,
    required this.onEndSaved,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            child: CustomTextField(
          label: '시작 시간',
          isTime: true,
          onSaved: onStartSaved,
        )),
        SizedBox(width: 16.0),
        Expanded(
            child: CustomTextField(
          label: '마감 시간',
          isTime: true,
          onSaved: onEndSaved,
        )),
      ],
    );
  }
}

class _Content extends StatelessWidget {
  final FormFieldSetter<String> onSaved;

  const _Content({
    required this.onSaved,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: CustomTextField(
      label: '내용',
      isTime: false,
      onSaved: onSaved,
    ));
  }
}

typedef ColorIdSetter = void Function(int id);

class _ColorPicker extends StatelessWidget {
  final List<CategoryColor> colors;
  final int? selectedColorId;
  final ColorIdSetter colorIdSetter;

  const _ColorPicker({
    required this.colors,
    required this.selectedColorId,
    required this.colorIdSetter,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 8.0,
      runSpacing: 10.0,
      children: colors
          .map(
            (e) => GestureDetector(
              onTap: () {
                colorIdSetter(e.id);
              },
              child: renderColor(
                e,
                selectedColorId == e.id,
              ),
            ),
          )
          .toList(),
    );
  }

  Widget renderColor(CategoryColor color, bool isSelected) {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Color(
          int.parse(
            'FF${color.hexCode}',
            radix: 16,
          ),
        ),
        border: isSelected
            ? Border.all(
                color: Colors.black,
                width: 4.0,
              )
            : null,
      ),
      width: 32.0,
      height: 32.0,
    );
  }
}

class _SaveButton extends StatelessWidget {
  final VoidCallback onpressed;

  const _SaveButton({
    required this.onpressed,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: ElevatedButton(
            onPressed: onpressed,
            style: ElevatedButton.styleFrom(
              primary: PRIMARY_COLOR,
            ),
            child: Text('저장'),
          ),
        ),
      ],
    );
  }
}

 

 

도저히 해결이 안되서 진도를 못나가고 있는 상황입니다 ㅠㅠ

 

확인 부탁드립니다! 감사합니다

해결했습니다. 일단 scheduleList에 변수 선언이 안되있었고, 홈스크린_scheduleList(selecteddate selectedday) 선언이 안되어 있었네요 ㅠㅠ

0

코드팩토리님의 프로필 이미지
코드팩토리
지식공유자

안녕하세요.

어딘가에서 selectedDate를 getter 형태로 사용하신것같아요.

붙여넣기 하신 부분이 에러가 아닐 것 같은 느낌인데 다시한번 확인 후 댓글 부탁해요

karismafish님의 프로필 이미지
karismafish

작성한 질문수

질문하기