Created
January 1, 2020 13:36
-
-
Save suragch/a05bade0738492d1686036d49edba0d2 to your computer and use it in GitHub Desktop.
View Model with an initialization method for Provider Architecture example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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