颤振问题文本窗口小部件,显示未显示错误

时间:2020-06-16 01:37:31

标签: flutter

这是我创建的Flutter代码,由于某种原因,底部始终出现的错误文本不会出现。我创建了一个类似于此的登录页面,并且工作正常,但在该页面中,我使用的是onChanged而不是onSaved。我尝试使用它,但是一旦我在使用onChanged时开始键入键盘,键盘就会出现并消失,所以我使用了onSaved并消失了。

import 'package:flutter/material.dart';
import 'package:note_taker/authenticate/auth.dart';
import 'package:note_taker/shared/constants.dart';

class SignUp extends StatefulWidget {

  final Function toggleView;

  SignUp({@required this.toggleView});

  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  @override
  Widget build(BuildContext context) {
    final AuthService _auth = AuthService();
    String _email;
    String _password;
    String error = '';
    final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

    Widget _buildHelloThere() {
      return Container(
        child: Column(
          children: [
            Container(
              child: Stack(
                children: [
                  Container(
                    // container for the HELLO TEXT
                    padding: EdgeInsets.only(
                      top: 80,
                      left: 20,
                      right: 0,
                      bottom: 0,
                    ),
                    child: Text(
                      'HELLO',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 60,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                  Container(
                    // container for the TEXT TEXT
                    padding: EdgeInsets.only(
                      top: 130,
                      left: 20,
                      right: 0,
                      bottom: 0,
                    ),
                    child: Text(
                      'NEW',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 60,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                  Container(
                    // container for the . TEXT
                    padding: EdgeInsets.only(
                      top: 130,
                      left: 160,
                      right: 0,
                      bottom: 0,
                    ),
                    child: Text(
                      'USER',
                      style: TextStyle(
                        color: Colors.teal,
                        fontSize: 60,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    }

    Widget _buildEmail() {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: TextFormField(
          decoration: textDecorationForInput.copyWith(
            labelText: 'Email',
            labelStyle: TextStyle(color: Colors.teal),
          ),
          validator: (value) {
            Pattern pattern =
                r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
            RegExp regex = new RegExp(pattern);
            if (value.isEmpty) {
              return 'Email Required';
            } else if (!regex.hasMatch(value)) {
              return 'Enter Valid Email';
            }
            return null;
          },
          onSaved: (newValue) {
            setState(() {
              _email = newValue;
            });
          },
        ),
      );
    }

    Widget _buildPassword() {
      return Container(
        padding: EdgeInsets.only(top: 30, left: 20, right: 20),
        child: TextFormField(
          decoration: textDecorationForInput.copyWith(
            labelText: 'Password',
            labelStyle: TextStyle(color: Colors.teal),
          ),
          validator: (value) {
            if (value.isEmpty) {
              return 'Password Required';
            } else if (value.length < 6) {
              return 'Password too Small';
            }
            return null;
          },
          onSaved: (newValue) {
            setState(() {
              _password = newValue;
            });
          },
          obscureText: true,
        ),
      );
    }

    Widget _createSubmitButton() {
      return Center(
        child: RaisedButton(
          color: Colors.teal,
          padding: EdgeInsets.symmetric(horizontal: 130, vertical: 10),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          child: Text(
            'Sign In',
            style: TextStyle(
              color: Colors.white,
              fontSize: 30,
              fontWeight: FontWeight.bold,
            ),
          ),
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              dynamic result =
                  await _auth.signUpWithEmailAndPassword(_email, _password);
              if (result == null) {
                setState(() {
                  error = 'Problem with creating account';
                });
              }
            }
          },
        ),
      );
    }

    Widget _createSignInButton() {
      // to toggle between between sign up and log in
      return FlatButton(
        padding: EdgeInsets.only(left: 320),
        onPressed: () {
          //toggleView;
          widget.toggleView();
        },
        child: Text(
          'Sign up',
          style: TextStyle(
            color: Colors.blue,
            fontSize: 20,
          ),
        ),
      );
    }

    // this screen is next
    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // build a text that says the word Hello
                // build a text that says New
                // build a tex that say User
                _buildHelloThere(),
                // create the text field for email
                SizedBox(
                  height: 40,
                ),
                _buildEmail(),
                // create the text field for password
                _buildPassword(),
                //log in button
                _createSignInButton(),
                SizedBox(
                  height: 90,
                ),
                // submit button
                _createSubmitButton(),
                // error print out
                Center(
                  child: Text(
                    error,
                    style: TextStyle(
                      color: Colors.red,
                      fontSize: 20,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以在下面复制粘贴运行完整代码
步骤1:在variables中声明build,必须将它们移到build之外,以避免Sing-In失败并且setState将重置这些变量< br /> 代码段

final AuthService _auth = AuthService();
String _email;
String _password;
String error = '';
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

@override
Widget build(BuildContext context) {

第2步:您不需要setState中的onSaved

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';

class AuthService {
  signUpWithEmailAndPassword(String email, String password) {
    return null;
  }
}

class SignUp extends StatefulWidget {
  final Function toggleView;

  SignUp({@required this.toggleView});

  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  final AuthService _auth = AuthService();
  String _email;
  String _password;
  String error = '';
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    Widget _buildHelloThere() {
      return Container(
        child: Column(
          children: [
            Container(
              child: Stack(
                children: [
                  Container(
                    // container for the HELLO TEXT
                    padding: EdgeInsets.only(
                      top: 80,
                      left: 20,
                      right: 0,
                      bottom: 0,
                    ),
                    child: Text(
                      'HELLO',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 60,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                  Container(
                    // container for the TEXT TEXT
                    padding: EdgeInsets.only(
                      top: 130,
                      left: 20,
                      right: 0,
                      bottom: 0,
                    ),
                    child: Text(
                      'NEW',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 60,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                  Container(
                    // container for the . TEXT
                    padding: EdgeInsets.only(
                      top: 130,
                      left: 160,
                      right: 0,
                      bottom: 0,
                    ),
                    child: Text(
                      'USER',
                      style: TextStyle(
                        color: Colors.teal,
                        fontSize: 60,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    }

    Widget _buildEmail() {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: TextFormField(
          decoration: InputDecoration(
            labelText: 'Email',
            labelStyle: TextStyle(color: Colors.teal),
          ),
          validator: (value) {
            Pattern pattern =
                r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
            RegExp regex = new RegExp(pattern);
            if (value.isEmpty) {
              return 'Email Required';
            } else if (!regex.hasMatch(value)) {
              return 'Enter Valid Email';
            }
            return null;
          },
          onSaved: (newValue) {
              _email = newValue;
          },
        ),
      );
    }

    Widget _buildPassword() {
      return Container(
        padding: EdgeInsets.only(top: 30, left: 20, right: 20),
        child: TextFormField(
          decoration: InputDecoration(
            labelText: 'Password',
            labelStyle: TextStyle(color: Colors.teal),
          ),
          validator: (value) {
            if (value.isEmpty) {
              return 'Password Required';
            } else if (value.length < 6) {
              return 'Password too Small';
            }
            return null;
          },
          onSaved: (newValue) {
              _password = newValue;
          },
          obscureText: true,
        ),
      );
    }

    Widget _createSubmitButton() {
      return Center(
        child: RaisedButton(
          color: Colors.teal,
          padding: EdgeInsets.symmetric(horizontal: 130, vertical: 10),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          child: Text(
            'Sign In',
            style: TextStyle(
              color: Colors.white,
              fontSize: 30,
              fontWeight: FontWeight.bold,
            ),
          ),
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              dynamic result =
                  await _auth.signUpWithEmailAndPassword(_email, _password);
              if (result == null) {
                setState(() {
                  error = 'Problem with creating account';
                });
              }
            }
          },
        ),
      );
    }

    Widget _createSignInButton() {
      // to toggle between between sign up and log in
      return FlatButton(
        padding: EdgeInsets.only(left: 320),
        onPressed: () {
          //toggleView;
          widget.toggleView();
        },
        child: Text(
          'Sign up',
          style: TextStyle(
            color: Colors.blue,
            fontSize: 20,
          ),
        ),
      );
    }

    // this screen is next
    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // build a text that says the word Hello
                // build a text that says New
                // build a tex that say User
                _buildHelloThere(),
                // create the text field for email
                SizedBox(
                  height: 40,
                ),
                _buildEmail(),
                // create the text field for password
                _buildPassword(),
                //log in button
                _createSignInButton(),
                SizedBox(
                  height: 90,
                ),
                // submit button
                _createSubmitButton(),
                // error print out
                Center(
                  child: Text(
                    error,
                    style: TextStyle(
                      color: Colors.red,
                      fontSize: 20,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SignUp(),
    );
  }
}