触摸TextFormField时键盘未打开

时间:2019-08-26 12:34:58

标签: flutter

我已经完成了用于登录的api调用,但是现在当我尝试在textformfields中编写内容时,键盘没有打开。

有以下代码可以检查我哪里出错了。

我指的是此示例网站。

https://medium.com/@kashifmin/flutter-login-app-using-rest-api-and-sqflite-b4815aed2149

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'dart:ui';
import 'package:flutter_routes_example/models/user.dart';
import 'package:flutter_routes_example/screens/login/login_screen_presenter.dart';

class LoginScreen extends StatelessWidget {
   final _scaffoldKey = new GlobalKey<ScaffoldState>();

   @override
   Widget build(BuildContext context) {
    return Scaffold(
    key: _scaffoldKey,
    resizeToAvoidBottomPadding: false,
    backgroundColor: Colors.white,
    appBar: new AppBar(
      automaticallyImplyLeading: true,
      leading: IconButton(
        icon: Icon(Icons.arrow_back),
        onPressed: () =>
        {
          if (Navigator.canPop(context))
            {Navigator.pop(context)}
          else
            {exit(0)}
        },
        color: Colors.black,
      ),
      backgroundColor: Colors.white,
      elevation: 0,
    ),
    body: Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 100),
          child: SingleChildScrollView(
            dragStartBehavior: DragStartBehavior.down,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('LOG IN',
                    style: TextStyle(fontFamily: 'Raleway', fontSize: 40)),
                Container(
                    margin: EdgeInsets.only(top: 5),
                    child: Text('Good to see you again',
                        style: TextStyle(
                            fontFamily: 'Raleway', fontSize: 15))),
                LoginForm(_scaffoldKey)
              ],
            ),
          ),
        )
      ],
    ));
  }
 }

 class LoginForm extends StatefulWidget {
 var _scafoldKey;

  LoginForm(var _scafoldKey){
  this._scafoldKey = _scafoldKey;
  }

 @override
 LoginFormState createState() {
  return LoginFormState(_scafoldKey);
 }
}

class LoginFormState extends State<LoginForm> implements 
  LoginScreenContract{

  var _isLoading = false;
  var _scaffoldKey;
  final _formKey = GlobalKey<FormState>();
  final FocusNode _emailFocus = FocusNode();
  final FocusNode _passwordFocus = FocusNode();
  LoginScreenPresenter _presenter;
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();


  LoginFormState(var _scafoldKey){
   _presenter = new LoginScreenPresenter(this);
   this._scaffoldKey = _scafoldKey;
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Container(
      margin: const EdgeInsets.only(top: 80),
      padding: const EdgeInsets.all(16.0),

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          _textFieldEmail(),
          _textFieldPassword(),
          _isLoading ? new CircularProgressIndicator() : 
          _raisedButton(),
          _textForgetPassword()
        ],
      ),
    ));
    }

  _textFieldEmail() {
    return TextFormField(
    obscureText: false,
    keyboardType: TextInputType.emailAddress,
    textInputAction: TextInputAction.next,
    focusNode: _emailFocus,
    onFieldSubmitted: (term) {
    _fieldFocusChange(context, _emailFocus, _passwordFocus);
    },
   style: TextStyle(fontFamily: 'Raleway', fontSize: 14),
   decoration: InputDecoration(
      labelText: 'Your Email',
      border: OutlineInputBorder(borderRadius: 
      BorderRadius.horizontal()),
      contentPadding: const EdgeInsets.all(15.0)),
      controller: _emailController,
     validator: (value) {
       if (value.isEmpty) {
         return 'Please enter email';
        } else if (!validateEmail(value)) {
      return 'Please enter valid email';
       }
       return null;
      },
     );
    }

   _textFieldPassword() {
     return Container(
      margin: const EdgeInsets.only(top: 20.0),
     child: TextFormField(
    obscureText: true,
    focusNode: _passwordFocus,
    textInputAction: TextInputAction.done,
    keyboardType: TextInputType.text,
    style: TextStyle(fontFamily: 'Raleway', fontSize: 14),
    decoration: InputDecoration(
        labelText: 'Password',
        border: OutlineInputBorder(borderRadius: 
        BorderRadius.horizontal()),
        contentPadding: const EdgeInsets.all(15.0)),
       controller: _passwordController,
       validator: (value) {
       if (value.isEmpty) {
        return 'Please enter password';
      } else if (value.length < 6 || value.length > 15) {
        return 'Password lenght should be 6 to 15 characters';
      }
        return null;
      },
     ),
    );
     }

   _fieldFocusChange(BuildContext context, FocusNode currentFocus,
         FocusNode nextFocus) {
      currentFocus.unfocus();
       FocusScope.of(context).requestFocus(nextFocus);
         }

      _raisedButton() {
          return Container(
        margin: const EdgeInsets.only(top: 40),
          child: RaisedGradientButton(
               child: Text(
                    'LOG IN',
                  style: TextStyle(color: Colors.white, 
            fontFamily: 'Raleway'),
           ),
          gradient: LinearGradient(
             colors: <Color>[
               Colors.deepOrange,
              Colors.deepOrange,
              Colors.redAccent
             ],
            ),
         onPressed: () {
              if (_formKey.currentState.validate()) {
              FocusScope.of(context).requestFocus(new 
             FocusNode());
            _submit();
           };
         }),
         );
          }

     _textForgetPassword() {
            return Container(
           margin: const EdgeInsets.only(top: 20),
             child: Text(
                    "Forgot your password?",
                      style: TextStyle(fontFamily: 'Raleway', 
                      color: Colors.black),
                           ),
                 );
                 }

           bool validateEmail(String 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 (!regex.hasMatch(value))
              return false;
         else
             return true;
             }

      void _submit() {
           String _email = _emailController.text.trim();
           String _password = _passwordController.text.trim();

          final form = _formKey.currentState;

        if (form.validate()) {
           setState(() => _isLoading = true);
             form.save();
           _presenter.doLogin(_email, _password);
           }
         }

          void _showSnackBar(String text) {
             _scaffoldKey.currentState.showSnackBar(new 
                   SnackBar(content: new Text(text)));
                }

           @override
          void onLoginError(String errorTxt) {
           _showSnackBar(errorTxt);
           setState(() => _isLoading = false);
             }

         @override
          void onLoginSuccess(User user) {
                 _showSnackBar(user.toString());
                 setState(() => _isLoading = false);
                }
              }

class RaisedGradientButton extends StatelessWidget {
       final Widget child;
     final Gradient gradient;
     final double width;
        final double height;
       final Function onPressed;

   const RaisedGradientButton({
         Key key,
         @required this.child,
          this.gradient,
         this.width = double.infinity,
           this.height = 50.0,
           this.onPressed,
             }) : super(key: key);

         @override
        Widget build(BuildContext context) {
           return Container(
          width: width,
             height: 50.0,
              decoration: BoxDecoration(
          gradient: gradient,
         boxShadow: [
            BoxShadow(
             color: Colors.grey[500],
             offset: Offset(0.0, 1.5),
             blurRadius: 1.5,
            ),
           ],
          borderRadius: BorderRadius.circular(50)),
       child: Material(
        color: Colors.transparent,
       child: InkWell(
           onTap: onPressed,
           child: Center(
              child: child,
            )),
         ),
      );
       }
       }

0 个答案:

没有答案