简体   繁体   English

Flutter:如何在单击编辑按钮时从列表数据填充表单并保存?

[英]Flutter: How to populate form from a list data on click edit button and save it?

I have a list which is hard coded at the beginning.我有一个一开始就硬编码的列表。 When i make an entry in the form, the form data is saved to list.当我在表单中输入时,表单数据将保存到列表中。 I want to get the data in my form of same index when i click on the update icon.当我单击更新图标时,我想以相同索引的形式获取数据。 The current screen is this.当前画面是这样的。

在此处输入图像描述

I want this output after clicking on Edit button.单击编辑按钮后,我想要这个 output。 Is there any way I can do this?有什么办法可以做到这一点吗?

在此处输入图像描述

Here is my Code.这是我的代码。

import 'package:flutter/material.dart';
import 'package:table/model.dart';

class Episode5 extends StatefulWidget {
  @override
  _Episode5State createState() => _Episode5State();
}

class _Episode5State extends State<Episode5> {
  TextEditingController nameController = TextEditingController();
  TextEditingController emailController = TextEditingController();

  final form = GlobalKey<FormState>();
  static var _focusNode = new FocusNode();
  User user = User();
  List<User> userList = [
    User(name: "a", email: "a"),
    User(name: "d", email: "b"),
    User(name: "c", email: "c")
  ];

  @override
  Widget build(BuildContext context) {
    Widget bodyData() => DataTable(
          onSelectAll: (b) {},
          sortColumnIndex: 0,
          sortAscending: true,
          columns: <DataColumn>[
            DataColumn(
                label: Text("Name"),
                numeric: false,
                tooltip: "To Display name"),
            DataColumn(
                label: Text("Email"),
                numeric: false,
                tooltip: "To Display Email"),
            DataColumn(
                label: Text("Update"),
                numeric: false,
                tooltip: "To Display Email"),
          ],
          rows: userList
              .map(
                (name) => DataRow(
                  cells: [
                    DataCell(
                      Text(name.name),
                    ),
                    DataCell(
                      Text(name.email),
                    ),
                    DataCell(
                      Icon(
                        Icons.edit,
                        color: Colors.black,
                      ),
                    ),
                  ],
                ),
              )
              .toList(),
        );

    return Scaffold(
      appBar: AppBar(
        title: Text("Data add to List Table using Form"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            bodyData(),
            Padding(
              padding: EdgeInsets.all(10.0),
              child: Form(
                key: form,
                child: Container(
                  child: Column(
                    children: <Widget>[
                      TextFormField(
                        controller: nameController,
                        focusNode: _focusNode,
                        keyboardType: TextInputType.text,
                        autocorrect: false,
                        onSaved: (String value) {
                          user.name = value;
                        },
                        maxLines: 1,
                        validator: (value) {
                          if (value.isEmpty) {
                            return 'This field is required';
                          }
                          return null;
                        },
                        decoration: new InputDecoration(
                          labelText: 'Name',
                          hintText: 'Name',
                          labelStyle: new TextStyle(
                              decorationStyle: TextDecorationStyle.solid),
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      TextFormField(
                        controller: emailController,
                        keyboardType: TextInputType.text,
                        autocorrect: false,
                        maxLines: 1,
                        validator: (value) {
                          if (value.isEmpty) {
                            return 'This field is required';
                          }
                          return null;
                        },
                        onSaved: (String value) {
                          user.email = value;
                        },
                        decoration: new InputDecoration(
                            labelText: 'Email',
                            hintText: 'Email',
                            labelStyle: new TextStyle(
                                decorationStyle: TextDecorationStyle.solid)),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Column(
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Center(
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                TextButton(
                                  child: Text("Add"),
                                  onPressed: () {
                                    if (validate() == true) {
                                      form.currentState.save();
                                      addUserToList(
                                        user.name,
                                        user.email,
                                      );
                                      clearForm();
                                    }
                                  },
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void addUserToList(name, email) {
    userList.add(User(name: name, email: email));
  }

  clearForm() {
    nameController.clear();
    emailController.clear();
  }

  bool validate() {
    var valid = form.currentState.validate();
    if (valid) form.currentState.save();
    return valid;
  }
}

You just have to update the TextEditingController text by passing in the corresponding User .您只需通过传入相应的User来更新TextEditingController文本。

Add this function to your stateful widget.将此 function 添加到您的有状态小部件。

void _updateTextControllers(User user) {
    setState(() {
      nameController.text = user.name;
      emailController.text = user.email;
    });
  }

Then your icon becomes an IconButton and it passes in the user from userList然后你的图标变成一个IconButton并从userList传入用户

rows: userList
              .map(
                (name) => DataRow(
                  cells: [
                    DataCell(
                      Text(name.name),
                    ),
                    DataCell(
                      Text(name.email),
                    ),
                    DataCell(
                      IconButton(
                        onPressed: () => _updateTextControllers(name), // new function here
                        icon: Icon(
                          Icons.edit,
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ],
                ),
              )
              .toList(),

I assume you're gonna want to eventually add User rows dynamically and not hard code them, in which case I suggest you implement a state management solution ie.我假设您最终希望动态添加User行而不是硬编码它们,在这种情况下,我建议您实施 state 管理解决方案,即。 GetX, Provider, Riverpod, Bloc etc... to handle that. GetX、Provider、Riverpod、Bloc 等……来处理这个问题。 But for now, this works with what you have.但就目前而言,这适用于你所拥有的。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过单击 Flutter 中的按钮,使用列表中的数据构建新容器 - Build new container with data from a list by click on a button in Flutter Flutter 如何将数据从 sqflite 填充到下拉列表 - Flutter How to populate data from sqflite to dropdown list 如何在从 api 获取数据时填充 Flutter 中的列表 - How to populate list in Flutter while fetching data from api 单击保存按钮时如何使此列可编辑并保存编辑数据? - how to make this column editable and save the edit data when click on save button? 如何刷新按钮上的列表小部件数据单击 FLUTTER - How to refresh a list widget data on a button click FLUTTER 如何在颤动中从列表视图中填充表单 - How to populate a form from a listview on tap in flutter 如何在颤动中单击按钮时显示从 api 获取的数据? - How to show the fetched data from api on a button click in flutter? Flutter - 无法将所有 json 数据从 api 响应编辑保存到可迭代列表:(无法从可迭代列表中获取数据) - Flutter - Can't save all json data to Iterable List from api response EDIT: ( Can't Fetch Data from iterable List) 如何将数据从 inappwebview 传递到点击按钮时颤动? - How to pass data from inappwebview to flutter on button click? 在颤振中,如何从自动生成的文本字段列表中保存数据 - in flutter, how do I save data from a list of autogenerated textfields
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM