플러터에서 양식 변수를 얻는 방법 (How to get form variables in flutter)


문제 설명

플러터에서 양식 변수를 얻는 방법 (How to get form variables in flutter)

플러터에 양식이 있고 버튼을 누르면 사용자를 등록하는 포스트 함수를 호출하지만 양식의 변수에 액세스할 수 없습니다.

접근하고 싶습니다. 게시물을 작성하고 사용자를 등록하기 위한 사용자 이름, 이메일 및 비밀번호 입력 값

나는 그것을 다른 위젯으로 나눴습니다. 여기 코드:

양식

이것은 내 등록 화면에 있는 양식 위젯입니다.

Form(
key: _formKey,
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
padding: EdgeInsets.symmetric(
horizontal: 40.0,
vertical: 60.0,
),
child: Column(
children: <Widget>[
new Container(
child: Image.asset(
'../../assets/logo‑feec.png',
width: 200,
),
padding: EdgeInsets.symmetric(vertical: 15),
alignment: Alignment.topCenter,
),
buildUsernameTF(),
SizedBox(
height: 30.0,
),
buildEmailTF(),
SizedBox(
height: 30.0,
),
buildPasswordTF(),
SizedBox(
height: 30.0,
),
buildConfirmPasswordTF(),
Container(
padding: EdgeInsets.symmetric(vertical: 25.0),
width: 200,
child: ElevatedButton.icon(
onPressed: () async {
if (_formKey.currentState.validate()) {
futureString = await resource.MyHttpService().registerUser(username, email, password);
/ Here we want to access the variables /

                        }
                      },

                      label: Text('Envia'),
                      icon: Icon(Icons.login),
                      style: ElevatedButton.styleFrom(
                        primary: Colors.white,
                        onPrimary: Colors.black,
                        shape: const BeveledRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(3))),
                      )),
                ),
                Container(
                  padding: EdgeInsets.all(5),
                  width: 200,
                  child: TextButton(
                    onPressed: () =&gt; RouterConfig.router.navigateTo(
                      context,
                      &quot;login&quot;,
                      transition: TransitionType.nativeModal,
                    ),
                    child: Text(&quot;Inicia sessió&quot;),
                  ),
                )
              ],
            )),
      )

</code></pre>

위젯

이것은 양식에서 호출되는 위젯입니다.

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

final TextEditingController _confirmPass = TextEditingController();
final TextEditingController _pass = TextEditingController();

Widget buildPasswordTF() {
return Container(
width: 600,
child: TextFormField(
controller: _pass,
obscureText: true,
decoration: const InputDecoration(
icon: Icon(Icons.lock),
hintText: 'Enter password',
labelText: 'Password *'),
validator: (password) {
if (password == null || password.isEmpty) {
return 'invalid Password';
}
return null;
},
),
);
}

Widget buildConfirmPasswordTF() {
return Container(
width: 600,
child: TextFormField(
controller: _confirmPass,
obscureText: true,
decoration: const InputDecoration(
icon: Icon(Icons.lock),
hintText: 'Enter password',
labelText: 'Password *'),
validator: (password) {
if (password == null || password.isEmpty) {
return 'Invalid Password';
}
if (password != _pass.text) {
return 'Passwords don\'t match';
}
return null;
},
),
);
}

Widget buildUsernameTF() {
return Container(
width: 600,
child: TextFormField(
decoration: const InputDecoration(
icon: Icon(Icons.person),
hintText: 'Enter Username',
labelText: 'Username'),
validator: (username) {
if (username == null || username.isEmpty) {
return 'Invalid Username';
}
return null;
},
),
);
}

Widget buildEmailTF() {
return Container(
width: 600,
child: TextFormField(
decoration: const InputDecoration(
icon: Icon(Icons.mail),
hintText: 'Enter email',
labelText: 'Email *'),
validator: (email) {
if (EmailValidator.validate(email) != true) {
return 'Invalid Email';
}
if (email == null || email.isEmpty) {
return 'Invalid Email';
}
return null;
},
),
);
}
</code></pre>


참조 솔루션

방법 1:

The answer to this will depend on your widget tree but ideally, you would be able to access the TextEditingControllers inside your TextFormFields.

You will need to create TextEditingControllers for each TextFormField:

TextEditingController emailController = TextEditingController();

And then when you submit, you need to access the controller and get the text.

onPressed: () async {
   if (_formKey.currentState.validate()) {
     futureString = await resource.MyHttpService().registerUser(username, email, password);
     /* Here we want to access the variables */
     print('Email text: ' + emailController.text);
     }
  },

(by Pol LópezJoe Muller)

참조 문서

  1. How to get form variables in flutter (CC BY‑SA 2.5/3.0/4.0)

#dart #forms #flutter-form-builder #flutter






관련 질문

경고 대신 오류로 "@required" 주석 ("@required" annotation as error instead of warning)

Flutter ThemeData가 텍스트에서 작동하지 않습니다 (Flutter ThemeData is not working for the Text)

Aqueduct 및 Dart: Future<List<T>>(T = ManagedObject)를 JSON으로 직렬화할 수 없습니다. (Aqueduct and Dart: Future<List<T>> (T = ManagedObject) can't be serialized to JSON)

나는 세 개의 텍스트 필드가 있는데 그 중 처음 두 개 중에서 선택하고 세 번째 필드로 작업하고 싶습니다. (I have three text fields, want to choose between first two of them, & work with third one)

각 페이지에 대한 동적 높이로 Flutter Carousel Slider 만들기 (Create a Flutter Carousel Slider with dynamic heigth for each page)

SMS를 보낼 때 flutter url_launcher의 해시 기호 뒤에 메시지 본문이 사라집니다. (Message body disappear after hash symbol in flutter url_launcher when send a SMS)

미래 방법을 조롱하고 'Null'유형을 얻지 않는 방법은 플러터에서 'Future<>'유형의 하위 유형이 아닙니다. (How to mock a future method and not get type 'Null' is not a subtype of type 'Future<>' in flutter)

【NoSuchMethodError】audio_service가 initState에서 시작되지 않습니다 (【NoSuchMethodError】audio_service does not start in initState)

플러터에서 양식 변수를 얻는 방법 (How to get form variables in flutter)

다른 프로세스에서 사용 중이기 때문에 Pub에서 항목을 삭제하지 못했습니다. (Pub failed to delete entry because it was in use by another process)

RenderViewport는 RenderSliver 유형의 하위를 예상했지만 RenderErrorBox 유형의 하위를 수신했습니다. (A RenderViewport expected a child of type RenderSliver but received a child of type RenderErrorBox)

Flutter에서 이름을 확인하는 방법은 무엇입니까? (How to validate Name in flutter?)







코멘트