app_module.dart 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import 'package:dartin/dartin.dart';
  2. import 'package:dio/dio.dart';
  3. import 'package:mvvm_flutter/helper/constants.dart';
  4. import 'package:mvvm_flutter/helper/shared_preferences.dart';
  5. import 'package:mvvm_flutter/model/repository.dart';
  6. import 'package:mvvm_flutter/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. ..addOthers(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. lazy<GithubRepo>(({params}) => GithubRepo(get(), get())),
  23. ]);
  24. /// Remote 模块
  25. ///
  26. /// 定义各网络接口服务的构造方式
  27. final remoteModule = Module([
  28. single<GithubService>(GithubService()),
  29. ]);
  30. /// Local 模块
  31. ///
  32. /// 定义数据库层及SharedPreference/KV等等本地存储的构造方式
  33. final localModule = Module([
  34. single<SpUtil>(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. }