Как получить значение TextField во флаттере

Я создал экран регистрации во флаттере. Я хочу получить адрес электронной почты и пароль в onPressedFlatButton.

Кто-нибудь знает, как это сделать на флаттере?

  Widget SignupPage() {
    return new Scaffold(body: Container(
      height: MediaQuery.of(context).size.height,
      decoration: BoxDecoration(
        color: Colors.white,
        image: DecorationImage(
          colorFilter: new ColorFilter.mode(
              Colors.black.withOpacity(0.05), BlendMode.dstATop),
          image: AssetImage('assets/images/mountains.jpg'),
          fit: BoxFit.cover,
        ),
      ),
      child: new Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(100.0),
            child: Center(
              child: Icon(
                Icons.headset_mic,
                color: Colors.redAccent,
                size: 50.0,
              ),
            ),
          ),
          new Row(
            children: <Widget>[
              new Expanded(
                child: new Padding(
                  padding: const EdgeInsets.only(left: 40.0),
                  child: new Text(
                    "EMAIL",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    color: Colors.redAccent,
                    width: 0.5,
                    style: BorderStyle.solid),
              ),
            ),
            padding: const EdgeInsets.only(left: 0.0, right: 10.0),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: TextField(
                    obscureText: true,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'PLEASE ENTER YOUR EMAIL',
                      hintStyle: TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 24.0,
          ),
          new Row(
            children: <Widget>[
              new Expanded(
                child: new Padding(
                  padding: const EdgeInsets.only(left: 40.0),
                  child: new Text(
                    "PASSWORD",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    color: Colors.redAccent,
                    width: 0.5,
                    style: BorderStyle.solid),
              ),
            ),
            padding: const EdgeInsets.only(left: 0.0, right: 10.0),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: TextField(
                    obscureText: true,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '*********',
                      hintStyle: TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 24.0,
          ),
          new Row(
            children: <Widget>[
              new Expanded(
                child: new Padding(
                  padding: const EdgeInsets.only(left: 40.0),
                  child: new Text(
                    "CONFIRM PASSWORD",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    color: Colors.redAccent,
                    width: 0.5,
                    style: BorderStyle.solid),
              ),
            ),
            padding: const EdgeInsets.only(left: 0.0, right: 10.0),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: TextField(
                    obscureText: true,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '*********',
                      hintStyle: TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 24.0,
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(right: 20.0),
                child: new FlatButton(
                  child: new Text(
                    "Already have an account?",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                    textAlign: TextAlign.end,
                  ),
                  onPressed: () => {},
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 50.0),
            alignment: Alignment.center,
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new FlatButton(
                    shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(30.0),
                    ),
                    color: Colors.redAccent,
                    onPressed: () => authHandler.handleSignInEmail(emailController.text, passwordController.text)
                        .then((FirebaseUser user) {
                      Navigator.push(context, new MaterialPageRoute(builder: (context) => HomePage()));
                    }).catchError((e) => print(e)),
                    child: new Container(
                      padding: const EdgeInsets.symmetric(
                        vertical: 20.0,
                        horizontal: 20.0,
                      ),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          new Expanded(
                            child: Text(
                              "SIGN UP",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    ));
  }
56
0
63 173
5
Перейти к ответу Данный вопрос помечен как решенный

Ответы 5

Ответ принят как подходящий

Создайте свой TextEditingController как глобальную переменную в своем классе State и установите ее в свой виджет TextField.

TextEditingController emailController = new TextEditingController();

....


TextField(
  controller: emailController,
  obscureText: true,
  textAlign: TextAlign.left,
  decoration: InputDecoration(
    border: InputBorder.none,
    hintText: 'PLEASE ENTER YOUR EMAIL',
    hintStyle: TextStyle(color: Colors.grey),
  ),
)

Теперь вы можете получить значение, используя:

emailController.text

Вы можете получить более подробную информацию здесь: https://flutter.dev/docs/cookbook/forms/retrieve-input

У меня 3 текстовых поля, мне нужно 3 TextEditingController?

Aderbal Nunes 03.10.2018 21:04

да, или вы можете использовать метод onChanged для каждого текстового поля и сохранить значение в локальную переменную для каждого текстового поля

diegoveloper 03.10.2018 22:05

@diegoveloper У меня есть 10 текстовых полей и полей раскрывающихся кнопок в форме. Есть ли способ получить значение всех элементов? Или мне придется получать значение по одному для каждого элемента с помощью функции TextEditingController.text? Пожалуйста, предложите. Спасибо.

Kamlesh 12.05.2021 09:48

Текстовое поле вызывает функцию обратного вызова onChanged всякий раз, когда пользователь изменяет текст в поле. Если пользователь указывает, что он завершил набор текста в поле (например, нажав кнопку на виртуальной клавиатуре), текстовое поле вызывает обратный вызов onSubmitted.

Используя эти обратные вызовы, мы можем установить instance variables и использовать эти переменные в onPress кнопки отправки.

другой более простой (на мой взгляд) вариант - добавить свойство onChanged внутри класса TextField, который будет содержать String

String enteredText .... TextField( onChanged: (newText) { enteredText = newText; },

TextEditingController emailController = new TextEditingController();
        ....
        
        TextField(
          controller: emailController,
          obscureText: true,
          textAlign: TextAlign.left,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: 'PLEASE ENTER YOUR EMAIL',
            hintStyle: TextStyle(color: Colors.grey),
          ),
        )

        emailController.text

Сделайте TextEditingController перед методом сборки.

TextEditingController yourControllerName = new TextEditingController();

Затем в TextField передайте контроллер следующим образом:

TextField(
           controller: yourNameController,
           // your extra stuff
          )

И предположим, что вы хотите получить к нему доступ в тексте, получите доступ к нему так:

Text(
     yourControllerName.text.toString(), // this will convert your controller to String
     )

Спасибо, надеюсь сработает !!!

Другие вопросы по теме