티스토리 뷰

안녕하세요.

오늘은 flutter에서 form을 만들 때 유용하게 사용할 수 있는 flutter_form_builder 모듈을 소개해보려 합니다.

 

모듈을 사용해 만든 화면은 아래와 같습니다. 

 

또한 조건을 충족하지 않을 시 에러 메시지를 띄울 수도 있으며 signauture를 작성할 수도 있습니다.

 

1. 설정

flutter에서 모듈을 사용하려면 pubspec.yaml에 사용할 모듈 이름버전을 적어주어야 합니다.

아래 사진과 같이 pubspec.yaml 에 dependecies 아래 적어주시면 됩니다.

flutter_form_builder: ^3.5.4

 

프로젝트에 적용하시려면 cmd 창에 명령어를 입력해주어야 됩니다.

cmd 창에서 작업 중인 프로젝트에 경로로 들어와주세요.

저는 D:\flutter\work-flutter\work\form_builder에서 작업 중이기 때문에 아래 사진과 같은 경로로 들어왔습니다.

사진으로는 잘 안보이지만 아래와 같이 나오셔야 됩니다. !

D:\flutter\work-flutter\work\form_builder>
// 작업 중인 폴더 경로>

 

그리고 프로젝트에 모듈을 적용시키는 명령어를 입력하도록 하겠습니다.

D:\flutter\work-flutter\work\form_builder>flutter packages get

D:\flutter\work-flutter\work\form_builder>flutter pub get

 

마지막으로 main.dart에 모듈을 import 해주셔야 됩니다.

import 'package:flutter_form_builder/flutter_form_builder.dart';

 

2. 용법

코드를 작성해보고 결과를 확인해보도록 하겠습니다.

main.dart 에서 코드 수정 후, 확인해 보시면 위에서 보셨던 예시 화면과 같은 화면을 보실 수 있습니다.

import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FormClass(),
    );
  }
}

class FormClass extends StatelessWidget {
  final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Form Builder"),
      ),
      body: ListView(
      padding: EdgeInsets.all(30.0),
      children: <Widget>[
        FormBuilder(
          key: _fbKey,
          initialValue: {
            'date': DateTime.now(),
            'accept_terms': false,
          },
          autovalidate: true,
          child: Column(
            children: <Widget>[
              FormBuilderDateTimePicker(
                attribute: "date",
                inputType: InputType.date,
                decoration: InputDecoration(labelText: "Appointment Time"),
              ),
              FormBuilderSlider(
                attribute: "slider",
                validators: [FormBuilderValidators.min(6)],
                min: 0.0,
                max: 10.0,
                initialValue: 1.0,
                divisions: 20,
                decoration: InputDecoration(labelText: "Number of things"),
              ),
              FormBuilderCheckbox(
                attribute: 'accept_terms',
                label: Text("I have read and agree to the terms and conditions"),
                validators: [
                  FormBuilderValidators.requiredTrue(
                    errorText: "You must accept terms and conditions to continue",
                  ),
                ],
              ),
              FormBuilderDropdown(
                attribute: "gender",
                decoration: InputDecoration(labelText: "Gender"),
                // initialValue: 'Male',
                hint: Text('Select Gender'),
                validators: [FormBuilderValidators.required()],
                items: ['Male', 'Female', 'Other']
                  .map((gender) =>
                    DropdownMenuItem(value: gender, child: Text("$gender")))
                  .toList(),
              ),
              FormBuilderTextField(
                attribute: "age",
                decoration: InputDecoration(labelText: "Age"),
                validators: [
                  FormBuilderValidators.numeric(),
                  FormBuilderValidators.max(70),
                ],
              ),
              FormBuilderSegmentedControl(
                decoration: InputDecoration(labelText: "Movie Rating (Archer)"),
                attribute: "movie_rating",
                options: List.generate(5, (i) => i + 1)
                  .map((number) => FormBuilderFieldOption(value: number))
                  .toList(),
              ),
              FormBuilderSwitch(
                label: Text('I Accept the tems and conditions'),
                attribute: "accept_terms_switch",
                initialValue: true,
              ),
              FormBuilderStepper(
                decoration: InputDecoration(labelText: "Stepper"),
                attribute: "stepper",
                initialValue: 10,
                step: 1,
              ),
              FormBuilderRate(
                decoration: InputDecoration(labelText: "Rate this form"),
                attribute: "rate",
                iconSize: 32.0,
                initialValue: 1,
                max: 5,
              ),
              FormBuilderCheckboxList(
                decoration: InputDecoration(labelText: "The language of my people"),
                attribute: "languages",
                initialValue: ["Dart"],
                options: [
                  FormBuilderFieldOption(value: "Dart"),
                  FormBuilderFieldOption(value: "Kotlin"),
                  FormBuilderFieldOption(value: "Java"),
                  FormBuilderFieldOption(value: "Swift"),
                  FormBuilderFieldOption(value: "Objective-C"),
                ],
              ),
              FormBuilderSignaturePad(
                decoration: InputDecoration(labelText: "Signature"),
                attribute: "signature",
                height: 100,
              ),
            ],
          ),
        ),
        Row(
          children: <Widget>[
            MaterialButton(
              child: Text("Submit"),
              onPressed: () {
                if (_fbKey.currentState.saveAndValidate()) {
                  print(_fbKey.currentState.value);
                }
              },
            ),
            MaterialButton(
              child: Text("Reset"),
              onPressed: () {
                _fbKey.currentState.reset();
              },
            ),
          ],
        )
        ],
      )
    );
  }
}

 

위 코드는 모듈을 만드신 분께서 예시로 작성해놓은 코드입니다.

자신이 개발하려는 프로젝트에 맞추어 코드를 수정해주시면 됩니다.

 

제가 파란색으로 밑줄 쳐놓은 부분이 Class 입니다.

각 Class 를 확인해보시면 사용할 수 있는 변수, 메소드가 있습니다.

Class 중 노랑 박스로 표시해놓은 클래스를 확인하려면 Ctrl + 마우스 왼쪽 키를 클릭하시면 확인하실 수 있습니다.

 

노랑 박스로 표시해놓은 Class 파일이 나타났습니다.

파란색으로 밑줄 쳐놓은 것이 Class에 변수입니다.

이 변수들을 활용해 속성과 스타일을 변경할 수 있습니다.

 

더 자세한 내용은 아래 주소를 참고해주세요.

https://pub.dev/packages/flutter_form_builder

 

flutter_form_builder | Flutter Package

Package to build Material Form with fields like TextField, DropDown, Switches etc. with ability to create custom FormFields and composability and reuse validation functions.

pub.dev

 

궁금하신 점이 있거나 잘못된 점이 있는 부분은 댓글을 통해 알려주세요. !

감사합니다. 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함