【问题标题】:Flutter: How to populate form from a list data on click edit button and save it?Flutter:如何在单击编辑按钮时从列表数据中填充表单并保存?
【发布时间】:2021-04-13 03:49:23
【问题描述】:

我有一个在开头硬编码的列表。当我在表单中输入时,表单数据将保存到列表中。当我单击更新图标时,我想以相同索引的形式获取数据。当前画面是这个。

点击编辑按钮后我想要这个输出。有什么办法可以做到吗?

这是我的代码。

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;
  }
}

【问题讨论】:

  • 提供table/model.dart 会有所帮助。

标签: flutter listview dart


【解决方案1】:

您只需通过传入相应的User 来更新TextEditingController 文本。

将此函数添加到您的有状态小部件。

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

然后你的图标变成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(),

我假设您最终会想要动态添加 User 行而不是硬编码它们,在这种情况下,我建议您实施状态管理解决方案,即。 GetX、Provider、Riverpod、Bloc 等……来处理这个问题。但就目前而言,这适用于你所拥有的。

【讨论】:

  • 我试过你提供的方法。它根据需要填充了表单。我要感谢你的帮助。虽然,我有另一个问题,但我想在更新表单后更新相应的字段。当我添加时,表单将新数据提交到列表。你能帮我解决那个问题吗?提前致谢
  • 我可以帮助你,但你应该把它作为一个单独的问题。这是两件不同的事情,您询问了更新按钮后面的文本字段,这就是我提供的解决方案。
  • 我点击了两次。带来不便敬请谅解。我会准备不同的问题。谢谢你的帮助:)
  • 我已经发布了这个问题。你能检查一下吗。 @Lorean.A。 stackoverflow.com/questions/67102033/…
  • 刚刚查看了答案。 Blokbergs 的回答对我来说看起来不错,应该对你有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 2012-05-12
  • 2019-05-12
  • 1970-01-01
相关资源
最近更新 更多