【问题标题】:Store information from forms in flutter在颤振中存储来自表单的信息
【发布时间】:2021-09-16 23:14:03
【问题描述】:

我是 Flutter 的初学者,我正在尝试创建一个药物追踪器应用程序。我想知道如何以类对象的形式存储用户输入。我创建了一个表单,它接受药丸的名称和时间作为复选框值 - 早上、下午、晚上和晚上。 在用户提供此信息后,我想将其存储为一个对象并将该对象存储在一个列表中。 后来我想用它来创建显示药丸名称和需要服用时间的容器。 我创建了一个单独的类。如何将用户输入存储为类对象?

这是类文件-

class MedInfo{
  late String name;
  late List<bool> medTime;

  MedInfo(String n,List<bool> t){
    name=n;
    medTime=t;
  }
}

这里是输入页面代码-

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'listItem.dart';
import 'medInfo.dart';

class MedPage extends StatefulWidget {
  @override
  _MedPageState createState()=> _MedPageState();
}

class _MedPageState extends State<MedPage> {

  GlobalKey<FormState> _formKey= GlobalKey<FormState>();

  List<MedInfo> items=[]; //maintains pills

  Future<MedInfo> showInformationDialog(BuildContext context) async{
    return await showDialog(context: context,
        builder: (context) {
      final TextEditingController customController= TextEditingController();

      bool isMorning = false;
      bool isAfternoon= false;
      bool isEvening=false;
      bool isNight=false;
      return StatefulBuilder(builder: (context,setState){
        return AlertDialog(
          title: Text("Name of the Pill"),
          content: Form(
              key: _formKey,
              child: SingleChildScrollView( child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  TextFormField(
                    controller: customController,
                    // validator: (value){
                    //   return value.isNotEmpty ? null : "Invalid Field";
                    // },
                    decoration: InputDecoration(hintText: "Enter name of the medicine"),
                  ),
                  Text("Choice Box"),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [

                      Text("Morning"),

                      Checkbox(
                          //title: Text("Morning"),
                          checkColor: Colors.white,
                          //fillColor: Colors.pink,

                          value: isMorning,
                          onChanged: (bool? checked){
                            setState((){
                              isMorning = checked!;
                            });
                          }),
                        ],
                      ),
                   Row(
                       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                       children: [

                       Text("Afternoon"),

                        Checkbox(
            //title: Text("Morning"),
                            checkColor: Colors.white,
              //fillColor: Colors.pink,

                            value: isAfternoon,
                            onChanged: (bool? checked){
                              setState((){
                           isAfternoon = checked!;
                        });
                         }),
            ],
        ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [

                      Text("Evening"),

                      Checkbox(
                        //title: Text("Morning"),
                          checkColor: Colors.white,
                          //fillColor: Colors.pink,

                          value: isEvening,
                          onChanged: (bool? checked){
                            setState((){
                              isEvening = checked!;
                            });
                          }),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [

                      Text("Night"),

                      Checkbox(
                        //title: Text("Morning"),
                          checkColor: Colors.white,
                          //fillColor: Colors.pink,

                          value: isNight,
                          onChanged: (bool? checked){
                            setState((){
                              isNight = checked!;
                            });
                          }),
                    ],
                  ),

                ],
              )
              )
          ),
          // content: TextField(
          //   controller: customController,
          // ),
          actions: <Widget>[
            MaterialButton(
                elevation: 5.0,
                child: Text("OK"),
                onPressed: (){
                  Navigator.of(context).pop(customController.text.toString()); // to go back to screen after submitting
                }
            )

          ],
        );
      });
    });
  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('My med app'),
      ),
      body: Center(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget> [
            Expanded(
              child: ListView.builder(
                //padding: const EdgeInsets.all(8),
                itemBuilder: (context,index){
                  return ReusableListItem(Color(0xFFd2fddf),items[index].name);
                },
                itemCount: items.length,


              ),
            ),

          ],
        ),

      ),

      floatingActionButton: FloatingActionButton(
        onPressed: (){
          print("Clicked");
          showInformationDialog(context).then((onValue){
            print(onValue);

            setState(() {
              items.add(onValue);

            });
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
enter code here

【问题讨论】:

    标签: android flutter dart user-interface


    【解决方案1】:

    TextFormField 还有一个onChanged 选项,它允许您设置一个回调,每次文本字段发生变化时都会调用该回调。

    https://flutter.dev/docs/cookbook/forms/text-field-changes 检查此以获取更多详细信息。

    【讨论】:

      【解决方案2】:

      有两种方法可以做到这一点, 我都提到了,看看什么适合你的需要:-

      #1。您可以使用 onFieldSubmitted 并像这样传递回调...

      TextFormField(
                      decoration: InputDecoration(labelText: 'pill name'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'Please enter a name!';
                        }
                      },
                      onFieldSubmitted: (value) {
                
                          pillName = value;
                        
                      },
                    ),
      

      您还可以为您的表单创建一个对象,然后每次需要保存数据时只需创建一个实例并调用如下:-

       onFieldSubmitted: (value) {
                        setState(() {
                          formObject.pillName = value;
                        });
                      },
      

      如果您想知道如何提交表单,那么您只需在表单小部件内添加一个按钮。

      这是一个交互式示例 => click me to see an example

      #2。如果您想在提交表单之前访问数据,那么您必须为每个字段制作 TextEditingController

      click 查看textEditingController的交互式示例。

      编码愉快...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-26
        • 2020-05-06
        • 1970-01-01
        • 2015-02-05
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 2013-09-07
        相关资源
        最近更新 更多