Flutter: Pass data between models using services

Viewed 157

I'm having trouble in passing data between 2 models using services. I've seen FilledStacks video on sharing data between models, but it is not working. I tried using his code files too, but it is not updating the ui on other screens.

I've created a simple project here. On screen One, I've a text and from screen Two, I'm updating this text using TextService, which is injected using locator. The problem i'm facing is that the UI is not updating. And yes I'm also calling notifyListeners()

I've attached the code below:

class OneViewModel extends ChangeNotifier {
  TextService _textService = locator<TextService>();

  String get text => _textService.myText;
}



class TwoViewModel extends ChangeNotifier {
  TextService _textService = locator<TextService>();

  void updateText(String updatedValue) {
    _textService.changeText(updatedValue);
    notifyListeners();
  }
}


//locator
GetIt locator = GetIt.instance;

void setupLocator() {
  locator.registerFactory(() => OneViewModel());
  locator.registerFactory(() => TwoViewModel());

  locator.registerLazySingleton(() => TextService());
}


//text service
class TextService {
  String _myText = 'This is Text';

  String get myText => _myText;

  void changeText(String newValue) {
    _myText = newValue;
  }
}

0 Answers
Related