首先,我对新想法持开放态度。
我使用 RepositoryProvider 在应用程序的开头提供一个 HomeRepository。我将需要在应用程序的大部分页面中使用此存储库中列出的属性。 我不想在不同的页面中获取所有这些。
class HomeRepository {
Dio? dio;
DioClient? dioC;
List<RelationType>? _relationTypes;
List<BusinessField>? _businessFieldList;
List<AddressType>? _addressTypeList;
List<City>? _cityList;
List<Country>? _countryList;
List<Gender>? _genderList;
HomeRepository._() {
dio = Dio();
if (dio != null) {
dioC = DioClient(dio!);
}
}
.... FetchFunctions() ...
例如,当我导航到 CompanyPage 时, 我创建了一个 CompanyRepository 的新实例:
class CompanyRepository extends HomeRepository{}
它会导致再次重新创建 HomeRepository,这就是为什么所有属性都按预期为空。
我该如何处理? 为这种情况创建一个单例存储库是个好主意吗?
HomeRepository 类中的单例示例:
class HomeRepository {
Dio? dio;
DioClient? dioC;
List<RelationType>? _relationTypes;
List<BusinessField>? _businessFieldList;
List<AddressType>? _addressTypeList;
List<City>? _cityList;
List<Country>? _countryList;
List<Gender>? _genderList;
// Singleton instance
static final HomeRepository _instance = HomeRepository._();
factory HomeRepository() {
return _instance;
}
HomeRepository._() {
dio = Dio();
if (dio != null) {
dioC = DioClient(dio!);
}
}
// ... FetchFunctions() ...
}