stacked icon indicating copy to clipboard operation
stacked copied to clipboard

How to call parent viewmodel `initialise` from child viewmodel?

Open joshiprashanthd opened this issue 5 years ago • 4 comments

I am creating a note taking app. This app has two views, one is to show grid view of all notes and second is to view and edit each note. Both views are bind with AllNotesViewModel and NoteViewModel respectively.

So when I tap a note in AllNotesView, it navigates to NoteView with tapped note information like title and body. When I done editing in NoteView and update the title and body I expect to see updated values in AllNotesView also. But when I go back to AllNotesView, the state is not updated. For this I want to call initialise method of AllNotesViewModel to update the state of AllNotesView.

But I can't seem to find way to do this. I can pass the AllNotesViewModel instance to NoteView and call initialise method on it, but I think there might be a better way to do this. Is there any way I can access the parent view model for situation like this?

joshiprashanthd avatar May 08 '21 12:05 joshiprashanthd

You can always call your AllNotesViewModel's initialise function whenever you return to this view

Future<void> navigateToNotesView() async {
    await _navigationService.navigateTo(Routes.noteView);
    initialise();
 }

Return a boolean value with _navigationService.back(result: true ) which will indicate that if AllNotesViewModel's initialise needs to be called based on the actions performed in NoteView.

// NoteViewModel
  _navigationService.back(result: isNoteEdited);
  
// AllNotesViewModel 
 Future<void> navigateToNotesView() async {
  final _navResult = await _navigationService.navigateTo(Routes.noteView) ;
    if (_navResult != null && _navResult) {
      initialise();
  }
}

hurbes avatar May 08 '21 15:05 hurbes

@hurbes is correct. @joshiprashanthd will close this issue now. We can re-open if you have more questions.

FilledStacks avatar May 10 '21 03:05 FilledStacks

Thanks @FilledStacks and @hurbes. You guys are great.

joshiprashanthd avatar May 10 '21 03:05 joshiprashanthd

@joshiprashanthd Hi, I know this issue is closed, but I still wanted to comment another possible solution for this. You could make use of the Reactivity by using a NoteService Class extending ReactiveServiceMixin that notifies your View models (extending ReactiveViewModel) about changes in your NoteService. In the NoteService you could place your logic for fetching and saving notes from the LocalStorage or your API. This means whenever a note in the NoteService Class is modified, your Views get rebuild automatically. Refer to https://pub.dev/packages/stacked at the ReactiveServiceMixin part. I hope this could help 😃

d3tr0id avatar May 15 '21 14:05 d3tr0id