Open wxqqh opened 3 months ago
this code is work for me but not elegant:
import 'package:get/get.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class AppService<T extends GetxService> extends GetxService {
@override
Future<T> onInit() async {
if (_initialized) return this as T;
super.onInit();
await init();
_initialized = true;
return this as T;
}
Future<void> init() async => throw UnimplementedError();
bool _initialized = false;
}
class DBService extends AppService {
@override
Future<void> init() async {
/// do sth. only called once
}
}
void main() {
setUpAll(() async {
await Get.putAsync(() => DBService().onInit());
DBService db = Get.find();
/// do sth. with DBService instance
});
}
Thanks for opening this issue, and you're absolutely right!
This is an architectural problem that I didn't think about at the time I created putAsync, to be honest, I used exactly the code you sent (I believe you've seen something like this on discord) for many years. About a year ago I created a Wrapper that allows me to do this in a more elegant way, I believe I can insert it into the package.
GetxService onInit in an error GetLifeCycle
The problem is that in GetLifeCycleBase, onInit is a FutureFunctional(), but it is executed synchronously. So the completion status of onInit CANNOT be obtained after Get.put is completed outside
the code is at there GetLifeCycleBase
example:
To Reproduce run the test case
Expected behavior
Get.putAsync
may get the onInit finish OR just like doc call onInit MANUALNow this code can work, but it is very cumbersome
Getx Version:
Describe on which device you found the bug: In test case