newbie dev
newbie dev

Reputation: 171

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.

enter image description here

I want this output after clicking on Edit button. Is there any way I can do this?

enter image description here

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

Upvotes: 0

Views: 2051

Answers (1)

Loren.A
Loren.A

Reputation: 5575

You just have to update the TextEditingController text by passing in the corresponding User.

Add this function to your stateful widget.

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

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. GetX, Provider, Riverpod, Bloc etc... to handle that. But for now, this works with what you have.

enter image description here

Upvotes: 2

Related Questions