app_module.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import 'package:dartin/dartin.dart';
  2. import 'package:dio/dio.dart';
  3. import '../helper/constants.dart';
  4. import '../helper/shared_preferences.dart';
  5. import '../model/repository.dart';
  6. import '../viewmodel/home_provide.dart';
  7. const testScope = DartInScope('test');
  8. /// ViewModel 模块
  9. ///
  10. /// 定义ViewModel的构造方式
  11. final viewModelModule = Module([
  12. factory<HomeProvide>(({params}) => HomeProvide(params.get(0), get())),
  13. ])
  14. ..withScope(testScope, [
  15. ///other scope
  16. // factory<HomeProvide>(({params}) => HomeProvide(params.get(0), get<GithubRepo>())),
  17. ]);
  18. /// Repository 模块
  19. ///
  20. /// 定义Repository 的构造方式
  21. final repoModule = Module([
  22. factory<GithubRepo>(({params}) => GithubRepo(get(), get())),
  23. ]);
  24. /// Remote 模块
  25. ///
  26. /// 定义各网络接口服务的构造方式
  27. final remoteModule = Module([
  28. factory<GithubService>(({params}) => GithubService()),
  29. ]);
  30. /// Local 模块
  31. ///
  32. /// 定义数据库层及SharedPreference/KV等等本地存储的构造方式
  33. final localModule = Module([
  34. single<SpUtil>(({params}) => spUtil),
  35. ]);
  36. final appModule = [viewModelModule, repoModule, remoteModule, localModule];
  37. /// AuthInterceptor
  38. ///
  39. /// 添加header认证
  40. class AuthInterceptor extends Interceptor {
  41. @override
  42. onRequest(RequestOptions options) {
  43. final token = spUtil.getString(KEY_TOKEN);
  44. options.headers.update("Authorization", (_) => token, ifAbsent: () => token);
  45. return super.onRequest(options);
  46. }
  47. }
  48. final dio = Dio()
  49. ..options = BaseOptions(baseUrl: 'https://api.github.com/', connectTimeout: 30, receiveTimeout: 30)
  50. ..interceptors.add(AuthInterceptor())
  51. ..interceptors.add(LogInterceptor(responseBody: true, requestBody: true));
  52. SpUtil spUtil;
  53. /// init
  54. ///
  55. /// 初始化 [spUtil] 并启动[DartIn]
  56. init() async {
  57. spUtil = await SpUtil.getInstance();
  58. // DartIn start
  59. startDartIn(appModule);
  60. }