강의

멘토링

커뮤니티

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

상우님의 프로필 이미지
상우

작성한 질문수

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

엘리베이트 버튼을 눌렀는데 화면이 어두워집니다

작성

·

419

0

색상 상태관리 강의에
isSelected 가 true 일때 테두리를 추가해주는 강의까지 따라왔는데 버튼을 누르면 바텀시트가 안뜨고 오류가 뜨면서 위 화면처럼 화면이 어둡게 뜹니다

 

에러 메세지가 너무 많아서 뭔지 모르겠네요...

Failed assertion: line 2001 pos 12: 'hasSize'

위와 같은 코드도 많이 보이고 그럽니다

 

설명이 부족할수있어서 작성한 코드 올려볼게요!

import 'package:calendar_schedular/component/custom_text_field.dart';
import 'package:calendar_schedular/const/color.dart';
import 'package:calendar_schedular/database/drift_database.dart';
import 'package:calendar_schedular/model/category_color.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:calendar_schedular/database/drift_database.dart';

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

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

class _ScheduleBottomSheetState extends State<ScheduleBottomSheet> {
  final GlobalKey<FormState> formKey = GlobalKey();

  // 처음엔 값이 없기때문에 null 허용 '?'
  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: Container(
        height: MediaQuery.of(context).size.height / 2 + bottomInset,
        color: Colors.white,
        child: Padding(
          padding: EdgeInsets.only(bottom: bottomInset),
          child: Padding(
            padding: const EdgeInsets.only(left: 8.0, right: 8.0, top: 16.0),
            child: Form(
              key: formKey,
              autovalidateMode: AutovalidateMode.always,
              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!,
                        );
                      }),
                  SizedBox(height: 16.0),
                  _SaveButton(
                    onPressed: onSavePressed,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  void onSavePressed() {
    // formKey는 생성을 했는데
    // Form 위젯과 결합이 안했을때
    if (formKey.currentState == null) {
      //우리는 formKey 값을 넣어줬기때문에 null 일수는 없다
      return;
    }

    if (formKey.currentState!.validate()) {
      print('에러가 없습니다.');
      formKey.currentState!.save();

      print('------------');
      print('startTime : $startTime');
      print('endTime : $endTime');
      print('content : $content');
    } 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,
      ),
    );
  }
}

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

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

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 8.0,
      runSpacing: 10.0,
      children: colors
          .map((e) => 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('저장'),
          ),
        ),
      ],
    );
  }
}

답변 1

0

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

안녕하세요!

크기를 지정해주지 않아서 생기는 에러입니다.

제 강의를 계속 잘 따라오셨다면 추후 강의에서 해결됩니다.

만약에 강의를 더 듣고도 해결되지 않는다면 다시한번 질문 주세요

상우님의 프로필 이미지
상우

작성한 질문수

질문하기