0

How can I define methods(functions) for a single model that is not a list with Flutter's Provider? For example, I have made 4 functions for a Model that is a list:

List<User> _userList = [];
List<User> get userList => _userList;
//method for getiing and setting the list of users
setUserList(List<User> list) {
    _userList = list;
    notifyListeners();
  }
// method for removing a single user
  deleteUser(User list) {
    _userList.remove(list);
    notifyListeners();
  }
//adding a new user
  addUser(User list) {
    _userList.add(list);
   notifyListeners();
  }
//updating the specific user
  updateUser(User user) {
    _userList [_userList.indexWhere((element) => element.id == user.id)] = user;
    notifyListeners();
  }

These all work fine (at least I think they work when I tested them :D) when it's a list of users, but how can I define these methods when it is a single object/item (single User) and not a list? The .add(), remove(), are methods that are available when there is a list, but not when there is a single item. What is the best approach for these CRUD model methods? The 'Read' is similar when it is a list:

User get user => _user;

//method for getting the user data
setUser(User user) {
    _user = user;
    notifyListeners();
  } 

but how I define the rest of the CRUD model like create(add), update and delete for a single model and not a list?

GrandMagus
  • 600
  • 3
  • 12
  • 37

1 Answers1

0

There is really not much difference when you are managing a list or a single item - just you will have methods that work on the single item. You do not show it above, but you should wrap your methods in a class (a "service") that maintains the data.

Here is an example authentication service that creates and deletes a User:

class AuthService with ChangeNotifier {
  User _user;
  User get user => _user;

  Future<void> _authenticate(String email, String password,
      [String name]) async {
    // This is where you authenticate or register the user, and update the state
    _user = User("dummy");
    return Future<void>(() {});
  }

  Future<void> register(String name, String email, String password) async {
    return _authenticate(email, password, name);
  }

  Future<void> login(String email, String password) async {
    return _authenticate(email, password);
  }

  Future<void> logout() async {
    _user = null;
    notifyListeners();
    return Future<void>(() {});
  }
}

If it is not clear please ask in the comments.

Patrick O'Hara
  • 1,999
  • 1
  • 14
  • 18