I have a list of class user showing with StateNotifier in one screen. Clicking on any item, opens the edit screen of that user. I have 2 questions to ask:
- Should I send user object In another screen and edit the user or create state provider (without auto dispose) of single object and set it before opening edit screen and access it on another screen.
- After edit the user, how to sync updated user object in user list screen (first screen).
Please feel free to ask any further detail. Thank you in advance.
CodePudding user response:
Should I send user object In another screen and edit the user or create state provider (without auto dispose) of single object and set it before opening edit screen and access it on another screen.
No, just send user object to edit screen, then after you edit done, pass data back to list screen by Navigator.pop(context, editedUser);
After edit the user, how to sync updated user object in user list screen (first screen).
On list screen :
Navigator.pushNamed(context, 'yourEditScreen', arguments: editUser).then((value) {
if (value != null) {
//update your state list;
}
});
CodePudding user response:
I won't cover how you send data between screens because it depends on what state manager you are using and there are actually many ways.
Assuming that you are on screen 1 after finishing screen 2, you have a list of old objects and a new object that has been modified. now you'll want to inject the changes into the old list object and call the update state
Example:
var objects = [{...}];
return ListView(
children: objects.map((object) {
final index = objects.indexOf(object);
onPressed() {
// handle will call when screen2 poped
handleEditedData(editedObject) {
// check object was edited and differences with old object (can override operator ==)
if (editedObject != null && editedObject != object) {
setState(() {
// replace old object by editedObject with the index
objects[index] = editedObject;
});
}
}
// push screen2 and wait to data from screen2 (using .pop with editedObj as parameter)
Navigator.of(context)
.pushNamed('screen2route', arguments: object)
.then(handleEditedData);
}
return ElevatedButton(onPressed: onPressed, child: const Text('edit'));
}).toList(),
);