我试图最终理解 Flutter 应用程序中的状态和反应性(多年来一直使用 MVVM 在 C# 中进行开发)
这几天一直在搞 Riverpod,看了几个 Youtube 视频,我有一个 Provider for Dio 客户端,如下:
@riverpod
Dio dio(DioRef ref) {
var options = BaseOptions(
baseUrl: myAwesomeEndpoint,
headers: {
HttpHeaders.contentTypeHeader: "application/json",
HttpHeaders.acceptHeader: "application/json",
HttpHeaders.authorizationHeader: "Basic fooBar",
},);
var dio = Dio(options);
return dio;
}
另外,我在一个类中有这个提供者作为我的服务存储库
@Riverpod(keepAlive: true)
class ApiService extends _$ApiService {
static const basePath = "/whseactivity";
@override
ApiService build() {
return ApiService();
}
Future<AllData> getAllData(DateTime date, String whseId) async {
String endpoint = "$basePath/GetDoorsActions?Date=$date&WhID=$whseId";
final response = // NEED TO GET THE DIO PROVIDER VALUE HERE
final json = response.data! as Map<String, dynamic>;
return AllData.fromJson(json);
}
}
如果我没有引用,如何在我的 ApiService 中的 getAllData() 函数内访问 Dio Provider?
将您的构建更改为:
late Dio dio;
@override
ApiService build() {
dio = ref.watch(dioProvider);
return ApiService();
}
现在您可以在其他方法中使用
dio
。