skip to Main Content

enter image description here

Referring to someone’s post, I’m trying to include a new attribute, Age which only receives integer value. However, when using TextEditingController and doing adding to the list, it’s about just String which usually doesn’t accept integer.

I want to input just numbers (integers) on the textfield ‘age’ and make the Age value accepted for adding to the list. I tried to use Parse on the class for ‘age’ but it causes an exception: The following FormatException was thrown building Builder:
Invalid number (at character 1)

My intention is to put the int values into the list as well. Is there any way to do that?

This is the code I’ve been working on.

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: Episode5()));

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

class User {
  String name;
  String age;
  int age1;

  User({this.name = '', this.age = ''}) : age1 = int.parse(age);
}

class _Episode5State extends State<Episode5> {
  TextEditingController nameController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  int currentIndex = 0;

  final form = GlobalKey<FormState>();
  static var _focusNode = new FocusNode();
  bool update = false;
  User user = User(age: '', name: '');
  List<User> userList = [
    User(name: "a", age: '12'),
    User(name: "d", age: '23'),
    User(name: "c", age: '19'),
  ];

  @override
  Widget build(BuildContext context) {
    Widget bodyData() => DataTable(
          onSelectAll: (b) {},
          sortColumnIndex: 0,
          sortAscending: true,
          columns: <DataColumn>[
            DataColumn(label: Text("Name"), tooltip: "To Display name"),
            DataColumn(label: Text("Age"), tooltip: "To Display Age"),
            DataColumn(label: Text("Update"), tooltip: "Update data"),
            DataColumn(label: Text("Delete"), tooltip: "Delete data"),
          ],
          rows: userList
              .map(
                (name) => DataRow(
                  cells: [
                    DataCell(
                      Text(name.name),
                    ),
                    DataCell(
                      Text(name.age),
                    ),
                    DataCell(
                      IconButton(
                        onPressed: () {
                          _updateTextControllers(name); // new function here
                        },
                        icon: Icon(
                          Icons.edit,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    DataCell(
                      IconButton(
                        onPressed: () =>
                            _deleteTextControllers(name), // new function here
                        icon: Icon(
                          Icons.delete,
                          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: (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: ageController,
                        keyboardType: TextInputType.text,
                        autocorrect: false,
                        maxLines: 1,
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'This field is required';
                          }
                          return null;
                        },
                        onSaved: (value) {
                          user.age = value!;
                        },
                        decoration: new InputDecoration(
                            labelText: 'Age',
                            hintText: 'Age',
                            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.age,
                                      );
                                      clearForm();
                                    }
                                  },
                                ),
                                TextButton(
                                  child: Text("Update"),
                                  onPressed: () {
                                    if (validate() == true) {
                                      form.currentState?.save();
                                      updateForm(user);
                                      clearForm();
                                    }
                                  },
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void updateForm(User user) {
    setState(() {
      User user = User(name: nameController.text, age: ageController.text);
      userList[currentIndex] = user;
    });
  }

  void _updateTextControllers(User user) {
    setState(() {
      nameController.text = user.name;
      ageController.text = user.age;
    });
  }

  void _deleteTextControllers(User user) {
    setState(() {
      int currentIndex = userList.indexOf(user);
      userList.removeAt(currentIndex);
    });
  }

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

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

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

2

Answers


  1. Chosen as BEST ANSWER

    Solution throughout the discussion in comments.

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() => runApp(MaterialApp(home: Episode5()));
    
    class Episode5 extends StatefulWidget {
      @override
      _Episode5State createState() => _Episode5State();
    }
    
    class User {
      String name;
      int? age1;
      User({
        required this.name,
        this.age1,
      });
    }
    
    class _Episode5State extends State<Episode5> {
      TextEditingController nameController = TextEditingController();
      TextEditingController ageController = TextEditingController();
      int currentIndex = 0;
    
      final form = GlobalKey<FormState>();
      static var _focusNode = new FocusNode();
      bool update = false;
      final User user = User(name: "", age1: int.tryParse(""));
      List<User> userList = [
        User(name: "a", age1: 12),
        User(name: "d", age1: 23),
        User(name: "c", age1: 19),
      ];
    
      @override
      Widget build(BuildContext context) {
        Widget bodyData() => DataTable(
              onSelectAll: (b) {},
              sortColumnIndex: 0,
              sortAscending: true,
              columns: <DataColumn>[
                DataColumn(label: Text("Name"), tooltip: "To Display name"),
                DataColumn(label: Text("Age"), tooltip: "To Display Age"),
                DataColumn(label: Text("Update"), tooltip: "Update data"),
                DataColumn(label: Text("Delete"), tooltip: "Delete data"),
              ],
              rows: userList
                  .map(
                    (name) => DataRow(
                      cells: [
                        DataCell(
                          Text(name.name),
                        ),
                        DataCell(
                          Text("${name.age1 ?? 0}"),
                        ),
                        DataCell(
                          IconButton(
                            onPressed: () {
                              _updateTextControllers(name); // new function here
                            },
                            icon: Icon(
                              Icons.edit,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        DataCell(
                          IconButton(
                            onPressed: () =>
                                _deleteTextControllers(name), // new function here
                            icon: Icon(
                              Icons.delete,
                              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: (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: ageController,
                            keyboardType: TextInputType.number,
                            inputFormatters: <TextInputFormatter>[
                              FilteringTextInputFormatter.digitsOnly
                            ],
                            autocorrect: false,
                            maxLines: 1,
                            validator: (value) {
                              if (value!.isEmpty) {
                                return 'This field is required';
                              }
                              return null;
                            },
                            onSaved: (value) {
                              user.age1 = int.tryParse(value ?? "");
                            },
                            decoration: new InputDecoration(
                                labelText: 'Age',
                                hintText: 'Age',
                                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.age1,
                                          );
                                          clearForm();
                                        }
                                      },
                                    ),
                                    TextButton(
                                      child: Text("Update"),
                                      onPressed: () {
                                        if (validate() == true) {
                                          form.currentState?.save();
                                          updateForm(user);
                                          clearForm();
                                        }
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    
      void updateForm(User user) {
        setState(() {
          User user = User(
              name: nameController.text, age1: int.tryParse(ageController.text));
          userList[currentIndex] = user;
        });
      }
    
      void _updateTextControllers(User user) {
        setState(() {
          nameController.text = user.name;
          ageController.text = user.age1.toString();
        });
      }
    
      void _deleteTextControllers(User user) {
        setState(() {
          int currentIndex = userList.indexOf(user);
          userList.removeAt(currentIndex);
        });
      }
    
      void addUserToList(name, age1) {
        setState(() {
          userList.add(User(name: name, age1: age1));
        });
      }
    
      clearForm() {
        nameController.clear();
        ageController.clear();
      }
    
      bool validate() {
        var valid = form.currentState!.validate();
        if (valid) form.currentState!.save();
        return valid;
      }
    }
    

  2. the parse method cant handle exception, like here you are trying to convert empty string'' to int. I will suggest using .tryParse and provide a default value on exception(null) case, or make age nullable.

     User({
        this.name = '',
        this.age = '',
      }) : age1 = int.tryParse(age) ?? 0;
    

    or

    class User {
      String name;
      String age;
      int? age1;
    
      User({
        this.name = '',
        this.age = '',
      }) : age1 = int.tryParse(age);
    }
    

    I will prefer with final and const constructor.

    class User {
      String name;
      int? age1;
      User({
        required this.name,
        this.age1,
      });
    }
    

    and creating instance

    final User user = User(name: "name", age1: int.tryParse("123"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search