import 'dart:io'; import 'package:dartin/dartin.dart'; import 'package:dio/dio.dart'; import 'package:dio_http_cache/dio_http_cache.dart'; import 'package:flutter/material.dart'; import 'package:package_info/package_info.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sport/config.dart'; import 'package:sport/provider/game_info_model.dart'; import 'package:sport/provider/login_info_model.dart'; import 'package:sport/router/navigator_util.dart'; import 'package:sport/services/api/login_api.dart'; import 'package:sport/services/api/resp.dart'; import 'package:sport/services/api/rest_client.dart'; import 'package:sport/utils/toast.dart'; mixin ConfigInject on State { int _os; String _version; void initState() { super.initState(); final config = Config.config; startDartIn([ Module([ single(({params}) { return DioCacheManager(CacheConfig(baseUrl: config.baseUrl)); }), single(({params}) { BaseOptions options = new BaseOptions( baseUrl: config.baseUrl, connectTimeout: 10000, receiveTimeout: 10000, ); // 两点就是直接返回自身对象 类似链式调用 return Dio(options) ..interceptors.add(inject().interceptor) ..interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) async { // if(!options.headers.containsKey("Content-Type")) // options.headers["Content-Type"] = "application/json"; if (_version == null) { _version = (await PackageInfo.fromPlatform()).version; } if (_os == null) { _os = Platform.isAndroid ? 1 : Platform.isIOS ? 2 : 3; } SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("token"); return options.merge(headers: {"token": token}, queryParameters: options.queryParameters..addAll({"ver": "$_version", "os": "$_os"})); }, onResponse: (Response response) async { if(response.request?.path?.contains("checkUpdate") == true){ return response; } if (response.data is Map) { Map resp = response.data; if (resp['code'] == -5) { ToastUtil.show("${resp['msg']}"); NavigatorUtil.goLogin(context); } else if (resp['code'] != 0) { String msg = resp['msg']; if (msg != null) ToastUtil.show("${resp['msg']}"); } } return response; })) ..interceptors.add(LogInterceptor(responseBody: true, responseHeader: false, requestBody: true)); }), // 注入实例 single(({params}) { final dio = inject(); return RestClient(dio); }), single(({params}) { final dio = inject(); return LoginApi(dio); }), // single(({params}) { // final dio = inject(); // return GameApi(dio); // }), ]), Module([ factory(({params}) => LoginInfoModel()), factory(({params}) => GameInfoModel()), ]) ]); } }