Home > Software design >  Add new user into listview upon clicking floating action button in flutter
Add new user into listview upon clicking floating action button in flutter

Time:09-01

I am a beginner in Flutter. I am trying to add a new user into list item widget to screen when floating action button is pressed. How do I achieve this? I am trying to create a list of items. When the floating action button is clicked, a dialog box is prompted and user is asked to enter details. I want to add a new user into the list item with these user input details. This is my user_page.dart file which I am calling in main.dart to display the user list.

main.dart

    @override
  Widget build(BuildContext context) {
    List users = User.fromJsonToList(allData());

    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xFF32937e),
          title: Text("UserList"),
          leading: IconButton(
            onPressed: () {},
            icon: Icon(Icons.computer),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
        floatingActionButton: FloatingActionButton(
          backgroundColor: Color(0xFF32937e),
          elevation: 5.0,
          child: Icon(Icons.add), //child widget inside this button
          onPressed: () {
            createAlertDialog(context).then((onValue) {
              setState(() {
                users.add(onValue);
              });
            });
          },
        ),
        body: Center(
            child: ListView.builder(
                itemCount: users.length,
                itemBuilder: (BuildContext context, int index) {
                  User user = users[index];
                  return ListTile(
                      title: Text(user.firstName),
                      subtitle: Text(user.role),
                      leading: Container(
                          clipBehavior: Clip.antiAlias,
                          height: 100,
                          width: 100,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Color(0xFF32937e),
                          ),
                          child: Image.network(
                            user.avatar.toString(),
                            fit: BoxFit.fill,
                            errorBuilder: (context, exception, stackTrace) {
                              return const Icon(Icons.error);
                            },
                          )),
                      onTap: () {});
                })));
  }

  Future<String> createAlertDialog(BuildContext context) async {
    TextEditingController customController = new TextEditingController();
    return await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("Name of the User"),
            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
                  })
            ],
          );
        });
  }

user_page.dart

    allData() {
  return [
    {
      "id": "6281d43e-97c9-45c7-8969-29debdfbb5f1",
      "avatar": "https://robohash.org/illumatquefuga.png?size=50x50&set=set1",
      "first_name": "Lenci",
      "last_name": "Gauche",
      "email": "[email protected]",
      "role": "Construction Worker"
    },
    {
      "id": "5fa6030e-7987-46c8-a5e0-aace7069d0e0",
      "avatar": null,
      "first_name": "Leigh",
      "last_name": "Binstead",
      "email": "[email protected]",
      "role": "Construction Worker"
    },

userList.dart

class User {
  String id;
  String? avatar;
  String firstName;
  String lastName;
  String email;
  String role;

  User({
    required this.id,
    required this.avatar,
    required this.firstName,
    required this.lastName,
    required this.email,
    required this.role,
  });

  static List<User> fromJsonToList(userDataJson) {
    var list = <User>[];
    for (var usr in userDataJson) {
      list.add(
        User(
          id: usr['id'],
          email: usr['email'],
          firstName: usr['first_name'],
          lastName: usr['last_name'],
          role: usr['role'],
          avatar: usr['avatar'],
        ),
      );
    }
    return list;
  }
}

CodePudding user response:

You can add user on press ok in your dialog then pop the dialog

eg

actions: <Widget>[
              MaterialButton(
                  elevation: 5.0,
                  child: Text("OK"),
                  onPressed: () {
final myuserData=User(firstName: customController.text...other fields))
 users.add(myuserData);
                    Navigator.of(context).pop(); // to go back to screen after submitting
                  })

on the other hand no need to return a string on dialog close as you can make your TextEditingController customController global.

CodePudding user response:

The thing is here, You have List<User>users, To add data on it, you need to provide a User model.

You've single TextFiled, for now just add name from getting text from it.

Firstly put user outside the build method.

  List<User> users = User.fromJsonToList(allData());
  @override
  Widget build(BuildContext context) {

And adding item will be

onPressed: () {
  createAlertDialog(context).then((onValue) {
    users.add(User(
        id: "null",
        avatar: "",
        firstName: onValue,
        lastName: "na",
        email: "",
        role: ""));
    setState(() {});
  });
},

To have others fields for model class you need to add more input filed on dialog and return a User from dialog.


  Future<User> createAlertDialog(BuildContext context) async {
    TextEditingController customController = TextEditingController();

    User user = User(
        id: "", avatar: '', firstName: "", lastName: "", email: "", role: "");
    return await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("Name of the User"),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  onChanged: (value) {
                    user.id = value;
                  },
                ),
                TextField(
                  onChanged: (value) {
                    user.firstName = value;
                  },
                ),
                TextField(
                  onChanged: (value) {
                    user.lastName = value;
                  },
                ),
              ],
            ),
            actions: <Widget>[
              MaterialButton(
                  elevation: 5.0,
                  child: Text("OK"),
                  onPressed: () {
                    Navigator.of(context).pop(user);
                  })
            ],
          );
        });
  }
}

And saving will be like

onPressed: () {
  createAlertDialog(context).then((onValue) {
    users.add(onValue);
    setState(() {});
  });
},

CodePudding user response:

First do this:

Future<String> createAlertDialog(BuildContext context) async {
    TextEditingController customController = new TextEditingController();
    var reault = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("Name of the User"),
            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
                  })
            ],
          );
        });

    if (reault != null) {
      return reault;
    } else {
      return '';
    }
  }

then :

createAlertDialog(context).then((onValue) {
              if (onValue.isNotEmpty) {
                User user = User(
                    id: '112',
                    avatar: null,
                    firstName: onValue,
                    lastName: '',
                    email: '',
                    role: '');
                setState(() {
                  users.add(user);
                });
              }
            });

enter image description here

  • Related