首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从登录屏幕中获取表单数据到我的控制器中可用的字符串中

如何从登录屏幕中获取表单数据到我的控制器中可用的字符串中
EN

Stack Overflow用户
提问于 2022-02-08 02:46:45
回答 2查看 422关注 0票数 0

我觉得这应该是很容易的事情,但我不知道,我有一切工作,我只需要使‘电子邮件’和‘密码’字段更改为任何用户输入。下面是我的控制器,通过HTTP发送数据

代码语言:javascript
运行
复制
 postData() async {
    try {
      var response = await http
          .post(Uri.parse("http://exampleIP/untitled/authentication/login.php"), body: {
        "username": 'email',   // needs to be what user inputs//
        "password": 'password' // needs to be what user inputs//

我知道没有所有的代码,但是代码可以工作,我只需要知道如何从表单中获取输入。

这是表单代码

代码语言:javascript
运行
复制
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutx/flutx.dart';
import 'package:harralander/images.dart';
import 'package:harralander/theme/app_theme.dart';


import '../controllers/login_controller.dart';

class LogInScreen extends StatefulWidget {
  const LogInScreen({Key? key}) : super(key: key);

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

class _LogInScreenState extends State<LogInScreen> {
  late ThemeData theme;
  late CustomTheme customTheme;

  late LogInController controller;
  late OutlineInputBorder outlineInputBorder;

  @override
  void initState() {
    super.initState();
    theme = AppTheme.theme;
    customTheme = AppTheme.customTheme;

    controller = FxControllerStore.putOrFind(LogInController());
    outlineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(4)),
      borderSide: BorderSide(
        color: Colors.transparent,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FxBuilder<LogInController>(
        controller: controller,
        builder: (controller) {
          return _buildBody();
        });
  }

  Widget _buildBody() {
    return Scaffold(
      body: Padding(
        padding: FxSpacing.x(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FxText.h3(
              'Log In',
              fontWeight: 700,
            ),
            FxSpacing.height(20),
            Form(
              key: controller.formKey,
              child: Column(
                children: [
                  TextFormField(
                    style: FxTextStyle.b2(),
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        filled: true,
                        isDense: true,
                        fillColor: customTheme.card,
                        prefixIcon: Icon(
                          FeatherIcons.mail,
                          color: theme.colorScheme.onBackground,
                        ),
                        hintText: "Email Address",
                        enabledBorder: outlineInputBorder,
                        focusedBorder: outlineInputBorder,
                        border: outlineInputBorder,
                        contentPadding: FxSpacing.all(16),
                        hintStyle: FxTextStyle.b2(),
                        isCollapsed: true),
                    maxLines: 1,
                    controller: controller.emailTE,
                    validator: controller.validateEmail,
                    cursorColor: theme.colorScheme.onBackground,
                  ),
                  FxSpacing.height(20),
                  TextFormField(
                    style: FxTextStyle.b2(),
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        filled: true,
                        isDense: true,
                        fillColor: customTheme.card,
                        prefixIcon: Icon(
                          FeatherIcons.lock,
                          color: theme.colorScheme.onBackground,
                        ),
                        hintText: "Password",
                        enabledBorder: outlineInputBorder,
                        focusedBorder: outlineInputBorder,
                        border: outlineInputBorder,
                        contentPadding: FxSpacing.all(16),
                        hintStyle: FxTextStyle.b2(),
                        isCollapsed: true),
                    maxLines: 1,
                    controller: controller.passwordTE,
                    validator: controller.validatePassword,
                    cursorColor: theme.colorScheme.onBackground,
                  ),
                ],
              ),
            ),
            FxSpacing.height(20),
            Align(
              alignment: Alignment.centerRight,
              child: FxButton.text(
                  onPressed: () {
                    controller.goToForgotPasswordScreen();
                  },
                  padding: FxSpacing.zero,
                  splashColor: customTheme.fitnessPrimary.withAlpha(40),
                  child: FxText.b3(
                    'Forgot password ?',
                    color: customTheme.fitnessPrimary,
                  )),
            ),
            FxSpacing.height(20),
            Row(
              children: [
                FxButton(
                    padding: FxSpacing.xy(16, 12),
                    onPressed: () {
                      controller.postData();
                    },
                    backgroundColor: customTheme.card,
                    splashColor: theme.colorScheme.onBackground.withAlpha(40),
                    elevation: 0,
                    borderRadiusAll: 4,
                    child: Row(
                      children: [
                        Image(
                          image: AssetImage(Images.google),
                          height: 17,
                          width: 17,
                        ),
                        FxSpacing.width(20),
                        FxText.l2(
                          'Login with Google',
                          fontWeight: 600,
                          color: theme.colorScheme.onBackground,
                        ),
                      ],
                    )),
                FxSpacing.width(20),
                Expanded(
                  child: FxButton(
                    padding: FxSpacing.y(12),
                    onPressed: () {
                      controller.postData();
                    },
                    backgroundColor: customTheme.fitnessPrimary,
                    elevation: 0,
                    borderRadiusAll: 4,
                    child: FxText.b2(
                      'Log In',
                      color: customTheme.fitnessOnPrimary,
                      fontWeight: 600,
                    ),
                  ),
                ),
              ],
            ),
            FxSpacing.height(20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FxText.b3(
                  'New to Harralander? ',
                ),
                FxButton.text(
                    onPressed: () {
                      controller.goToRegisterScreen();
                    },
                    padding: FxSpacing.zero,
                    splashColor: customTheme.fitnessPrimary.withAlpha(40),
                    child: FxText.b3(
                      'Register',
                      color: customTheme.fitnessPrimary,
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

谢谢

EN

回答 2

Stack Overflow用户

发布于 2022-02-08 03:22:44

尝试在您的LogInController上声明一个TextEditingController

***

代码语言:javascript
运行
复制
  class LogInController extends GetxController{
 // xample as your textediting as this
 final emailTE = TextEditingController() 
     , passwordTE = TextEditingControler();

 callToLoging() async{
    //validate first as you use formKey
   if(formKey.currentState!.validate()){
        //call the loginApiService 
        await LoginApiService.postData(
            email: emailTE.value!.text // or email!.text,
            password : passwordTE.value!.text // or password!.text,
             );
      }
  }


  }

  class LoginAPIService{
    
  //Use Future or static it depends on you
  static postData({String? email , String? password}) async {
        try {
          var response = await http
              .post(Uri.parse("http://exampleIP/untitled/authentication/login.php"), body: {
            "username": email ?? "",   // needs to be what user inputs//
            "password": password ?? ""});
       } catch(e){
          
       }
    }
   
  }

如果有什么事情发生的话,请告诉我。

票数 0
EN

Stack Overflow用户

发布于 2022-02-08 05:06:14

--您必须使用TextEditingController来获取用户输入,并通过使用.text方法将这些输入存储在变量或访问中。例:

代码语言:javascript
运行
复制
TextEditingController _passwordController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();

String? uName;
String? pwd;

//inside from:
//we can get data using 
uName = _emailController.text;
pwd = _passwordController.text;
//or we can pass this directly as a parameter like this:
_passwordController.text 

进口‘包装:颤振/材料。飞镖’;进口‘包装:颤振/验证。省道’;

代码语言:javascript
运行
复制
class LoginFormWithAutoValidation extends StatefulWidget {
  @override
  _LoginFormWithAutoValidationState createState() => _LoginFormWithAutoValidationState();
}

class _LoginFormWithAutoValidationState extends State<LoginFormWithAutoValidation> {

  TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);
  
  TextEditingController _passwordController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();

  final _formKey = new GlobalKey<FormState>();

  String _email;
  String _password;
 

  bool _autoValidate = false;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.green[400],
      body: Center(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15),
              ),
              color: Color(0xffF3F3F3),
              elevation: 5,
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Form(
                  key: _formKey,
                  autovalidate: _autoValidate,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[

                      Center(
                          child: Text(
                        "Your Logo Here",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 25,
                        ),
                      )),
                      SizedBox(height: 25.0),

             // TextFormField for email address

                      TextFormField(
                        keyboardType: TextInputType.emailAddress,
                        autofocus: false,
                        controller: _emailController,
                        validator: validateEmail,
                        onSaved: (value) => _email = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          hintText: "Email",
                          border: OutlineInputBorder(
                           borderRadius:BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

            // TextFormField for email address

                      TextFormField(
                        autofocus: false,
                        controller: _passwordController,
                        validator: validatePassword,
                        onSaved: (value) => _password = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                         hintText: "Password",
                         border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

                      Divider(color: Colors.black),      // divider

                      SizedBox(height: 20.0),

                      Material(                   // login button
                        elevation: 5.0,
                        borderRadius: BorderRadius.circular(20.0),
                        color: Colors.green,
                        child: MaterialButton(
                          minWidth: MediaQuery.of(context).size.width,
                 padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          onPressed: () {


                            if (_formKey.currentState.validate()) {
                              Navigator.push(context,
                               MaterialPageRoute(builder: (context) {
                                return LoginFormWithAutoValidation();
                              }));
                            } else {
                              setState(() {                    
                             // validation error
                                _autoValidate = true;
                              });
                            }
                          },
                          child: Text("Login",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20)),
                        ),
                      ),
                      SizedBox(height: 10.0),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71028015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档