Skip to content

Instantly share code, notes, and snippets.

@suragch
Created January 1, 2020 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suragch/a05bade0738492d1686036d49edba0d2 to your computer and use it in GitHub Desktop.
Save suragch/a05bade0738492d1686036d49edba0d2 to your computer and use it in GitHub Desktop.
View Model with an initialization method for Provider Architecture example
import 'package:flutter/foundation.dart';
class CounterViewModel extends ChangeNotifier {
int _counter = 0;
int get counter => _counter;
WebApi _webApi = serviceLocator<WebApi>(); // <-- service
Future loadData() async { // <-- load initial data
_counter = await _webApi.fetchValue();
notifyListeners();
}
void increment() {
_counter++;
notifyListeners();
}
}
// Fake service locator. Use GetIt in a real app.
// Or inject the service in the view model constructor.
WebApi serviceLocator<T>() {
return WebApi();
}
// Fake web api
class WebApi {
Future<int> fetchValue() => Future.delayed(Duration(seconds: 2), () => 11);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment