将表单分解为多个小部件,并与这些小部件进行交互 [英] break a form into multiple widget and interact with those widget in flutter

查看:54
本文介绍了将表单分解为多个小部件,并与这些小部件进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,为了决定代码的可重用性,我决定将其分成多个小部件.我遇到的问题我不知道如何与每个组件进行交互.例如,如果主窗体声明了一个变量,我如何在存储在不同dart文件中的自定义文本字段小部件中访问该变量.

i have a form which i decided to break into multiple widget for code re- usability. the problem i am having i dont know how to interact with each components. for example, if the main form declare a variable, how do i access that variable in the custom textfield widget which is store in a different dart file.

下面是我的代码

dart表单文件(main.dart)

form dart file (main.dart)

import 'package:flutter/material.dart';
import 'package:finsec/widget/row_text_input.dart';
import 'package:finsec/widget/text_form_field.dart';
import 'package:finsec/widget/save_button.dart';
import 'package:finsec/utils/strings.dart';
import 'package:finsec/utils/dimens.dart';
import 'package:finsec/utils/colors.dart';
import 'package:finsec/widget/column_text_input.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    title: 'Simple Interest Calculator App',
    home: ThirdFragment(),
    theme: ThemeData(
        brightness: Brightness.dark,
        primaryColor: Colors.indigo,
        accentColor: Colors.indigoAccent),
  ));
}

class ThirdFragment extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ThirdFragmentState();
  }
}

class _ThirdFragmentState extends State<ThirdFragment> {

  var _formKey = GlobalKey<FormState>();
  var _currentItemSelected = '';
  bool isError = false;
  bool isButtonPressed = false;

  @override
  void initState() {
    super.initState();
  }



  TextEditingController amountController = TextEditingController();
  TextEditingController frequencyController = TextEditingController();


  @override
  Widget build(BuildContext context) {
    TextStyle textStyle = Theme.of(context).textTheme.title;

    return Scaffold(
      appBar: AppBar(
        title: Text('Simple Interest Calculator'),
      ),
      body: Form(
        key: _formKey,      
        child: SingleChildScrollView(
          child: Column (children: [
            Padding(
              padding: EdgeInsets.only(top: 10.0, bottom: 5.0, left: 15.0, right: 15.0),
              child: CustomTextField(textInputType:TextInputType.number,
                textController: amountController,
                errorMessage:'Enter Income Amount',
                labelText:'Income Amount for testing'),
            ),
            RowTextInput(inputName: 'Frequency:',
              textInputType: TextInputType.number,
              textController: frequencyController,
              errorMessage: 'Choose Income Frequency',
              labelText: 'Income Amount for testing'
            ),
            RowTextInput(inputName: 'Date Paid:',
                textInputType: TextInputType.number,
                textController: datePaidController,
                errorMessage: 'Pick Income Payment Date',
                labelText: 'Income Amount for testing'
            ),

            SizedBox(height: 20),


          Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                MaterialButton(
                  height: margin_40dp,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(margin_5dp)),
                  minWidth: (MediaQuery.of(context).size.width * .9) / 2,
                  color: Theme.of(context).primaryColor,
                  textColor: white,
                  child: new Text(save),
                  onPressed: () => {
                  setState(() {
                  if (_formKey.currentState.validate()) {
                    // amountController.text.isEmpty ? amountController.text='Value require' : amountController.text='';
                  //this.displayResult = _calculateTotalReturns();
                  }
                  })
                  },
                  splashColor: blueGrey,
                ),
                MaterialButton(
                  height: margin_40dp,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(margin_5dp)),
                  minWidth: (MediaQuery.of(context).size.width * .9) / 2,
                  color: Theme.of(context).primaryColor,
                  textColor: white,
                  child: new Text(save_and_continue),
                  onPressed: () => {},
                  splashColor: blueGrey,
                )
              ])
          ]
          ),
      ),
}

RowTextInput是另一个包含此代码的dart文件. RowTextInput.dart

RowTextInput is a different dart file that contains this code. RowTextInput.dart

import 'package:flutter/material.dart';
import 'package:finsec/utils/hex_color.dart';

class CustomTextField extends StatelessWidget {
  CustomTextField({
    this.textInputType,
    this.textController ,
    this.errorMessage,
    this.labelText,
  });

  TextInputType textInputType;
  TextEditingController textController;
  String errorMessage, labelText;


  @override
  Widget build(BuildContext context) {
    bool isError = false;
    return  Container(
      child: TextFormField(
        keyboardType: textInputType,
        style: Theme
              .of(context)
              .textTheme
              .title,
        controller: textController,
        validator: (String value) {
            if (value.isEmpty) {
              return errorMessage;
            }
        },
        decoration: InputDecoration(
          labelStyle: TextStyle(
            color: Colors.grey,
            fontSize: 16.0
          ),
        contentPadding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),  //size of textfield
        errorStyle: TextStyle(
          color: Colors.red,
          fontSize: 15.0
        ),
        border: OutlineInputBorder(
          borderSide:  BorderSide(width:5.0),
          borderRadius: BorderRadius.circular(5.0)
        )
        )
      ),
    );
  }
}


我想从RowTextInput.dart访问位于main.dart中的isError和isButtonPressed变量,并能够分配值.然后main.dart应该能够看到在RowTextInput.dart文件中分配的那些值.

i want to access isError and isButtonPressed variables located in main.dart from RowTextInput.dart and be able to assign values. main.dart should then be able to see those values assign in RowTextInput.dart file.

此外,我想将MaterialButton按钮移动到其自己的窗口小部件文件(button.dart)中,但随后我不知道当单击按钮或检查isError和值时,此dart文件将如何与main.dart文件进行交互.按下IS按钮.基本上,我将表单分为不同的组件(文本字段和按钮),并将它们存储在自己的单独文件中.但我希望所有文件main.dart,rowintputtext,button.dart(new)都能看到main.dart中变量的值并更改值.这可能吗?有没有更简单的方法?

also,i want to move the MaterialButton button in its own widget file (button.dart) but then i dont know how this dart file will interact with the main.dart file when button is click or to check values of isError and IS button pressed. basically, i am breaking the form into different components (textfield and button) and store them in their own separate file. but i want all the files main.dart, rowintputtext, button.dart(new) to be able to see values of variables in main.dart and change the values. is this possible? is there an easier way?

预先感谢

推荐答案

如果考虑一下.在Flutter中,Button和RawMaterialButton已经在其他文件中.并能够完全按照您的意愿进行操作.

If you think about it. In Flutter the Button and RawMaterialButton are already in other files. And the manage to do exactly what you want.

您应该创建一个文件mycustomButtons.dart.
在文件中,您应该创建一个将构建Buttons ...的类.
但是必须在其构造函数actionSave actionSaveAndContinue中具有两个参数.

You should create a File mycustomButtons.dart.
In the file you should create a class that will build your Buttons...
But it must has two parameters in it's constructor actionSave actionSaveAndContinue.

然后您将在主目录中创建两个函数,例如:

You will then create two functions in your main something like:

      void _save() {
          setState(() {
              if (_formKey.currentState.validate()) {
                // amountController.text.isEmpty ? amountController.text='Value require' : amountController.text='';
              //this.displayResult = _calculateTotalReturns();
              }
          })
      }

然后,您应该将创建的函数作为参数传递:

Then you should pass your created functions as parameters:

    MyCustomButtons(actionSave: _save, actionSaveAndContinue: _saveAndContinue)

因此,该按钮将具有所有需要的信息来更新main.dart变量.

So the button will have all needed information to update your main.dart variables.

textField几乎相同.但是您将需要传递验证功能和TextEditingController.

The textField is pretty much the same. But you will need pass a validation function and a TextEditingController.

您可以看到RawnMaterialButtonTextFormField的字体,以了解它们如何接收(并将)数据从一个类传递到另一类.

You can see the font of RawnMaterialButton, TextFormField to see how they receive (and pass) data from one class to an other.

这篇关于将表单分解为多个小部件,并与这些小部件进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆