// Injection 方法 class Injection{ static Future<void> init() async { // shared_preferences await Get.putAsync(() => SharedPreferences.getInstance()); Get.lazyPut(() =>RequestRepository()); } } // 入口函数 void main() async{ WidgetsFlutterBinding.ensureInitialized(); await Injection.init(); }
这里通过 putAsync 注入一个异步依赖,懒加载一个 Ruquest的依赖
在其它地方通过Get.find
来注入依赖, 如下
class BaseGetController extends GetxController{ ///HTTP请求仓库 late RequestRepository request; @override void onInit() { super.onInit(); request = Get.find<RequestRepository>(); } }
///获取搜索历史记录 static List<String> getSearchHistory() { SharedPreferences sp = Get.find<SharedPreferences>(); try { var json = sp.getStringList(SPKey.searchHistory); if (json == null) { return []; } else { return json; } } catch (e) { debugPrint(e.toString()); return []; } }