Flutter GetX Get Service
这个类就像一个 GetxController ,它共享相同的生命周期onInit() 、onReady()、onClose() 。但里面没有 “逻辑”。它只是通知GetX的依赖注入系统,这个子类不能从内存中删除。所以如果你需要在你的应用程序的生命周期内对一个类实例进行绝对的持久化,那么就可以使用GetxService 。
所以这对保持你的 "服务 "总是可以被Get.find()获取到并保持运行是超级有用的。比如ApiService , StorageService , CacheService 。
定义并使用ApiService
第一步、定义一个ApiService
新建 services/api.dart
import 'package:get/get.dart';
class ApiService extends GetxService {
String api() {
return "http://jdmall.itying.com/";
}
}
第二步、注册服务
import './services/api.dart';
void main() async{
await initServices();
runApp(const MyApp());
}
Future<void> initServices() async {
print("初始化服务");
await Get.putAsync(() async => ApiService());
print("所有服务启动");
}
第三步、调用服务
import './services/api.dart';
Get.find<ApiService>().api()
定义并使用StorageService
第一步、定义一个StorageService
新建 services/storage.dart
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
class StorageService extends GetxService {
Future<void> getCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int count = (prefs.getInt("counter") ?? 0) + 1;
print("count 的值为: $count");
await prefs.setInt("counter", count);
}
}
第二步、注册服务
import './services/api.dart';
import './services/storage.dart';
void main() async{
await initServices();
runApp(const MyApp());
}
Future<void> initServices() async {
print("初始化服务");
await Get.putAsync(() async => ApiService());
await Get.putAsync(() async => StorageService());
print("所有服务启动");
}
调用服务
import './services/storage.dart';
Get.find<StorageService>().getCounter();