我用的是BLoC和workmanager图书馆.
实际上,代码运行得很好.但是,看起来像是气味代码.
我的问题是: 我必须为包装我的MainApp()部件的MultiRepositoryProvider初始化我的所有存储库.在这一点上,基本的东西.
void main() async {
final RepositoryOne repoOne = RepositoryOne();
final RepositoryTwo repoTwo = RepositoryTwo();
runApp(
MultiRepositoryProvider(
providers: [
RepositoryProvider(
create: (context) => repoOne,
),
RepositoryProvider(
create: (context) => repoTwo,
),
],
child: const MyApp(),
),
);
}
但是,当我为我的工作经理声明一个工作时,我必须重新初始化其中的一些存储库.
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
switch (task) {
case 'synchronize':
final RepositoryOne repoOne = RepositoryOne();
final RepositoryTwo repoTwo = RepositoryTwo();
List<int> result = await repoOne.synchronize();
if (result.isNotEmpty) {
await repoTwo.doThings(result);
}
break;
}
return Future.value(true);
});
}
我try 了几种方法在同一位置导出存储库初始化,但没有成功……
有没有人有一个初始化to not duplicate个存储库的 idea ?
Solution chosen个
为了做到这一点,我go 掉了服务定位器库.
我做了什么:
late RepositoryOne repoOne;
late RepositoryTwo repoTwo;
late RepositoryThree repoThree;
late RepositoryFour repoFour;
void initDependenciesStuff() {
repoOne = RepositoryOne();
repoTwo = RepositoryTwo();
}
void initAnotherDependenciesStuff() {
repoThree = RepositoryThree();
repoFour = RepositoryFour();
}
void main() {
initDependenciesStuff();
initAnotherDependenciesStuff();
runApp(
MultiRepositoryProvider(
providers: [
RepositoryProvider(
create: (context) => repoOne,
),
RepositoryProvider(
create: (context) => repoTwo,
),
RepositoryProvider(
create: (context) => repoThree,
),
RepositoryProvider(
create: (context) => repoFour,
),
],
child: const MyApp(),
),
);
}
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
switch (task) {
case 'firstThing':
initDependenciesStuff();
List<int> stuff = repoOne.fetchStuff();
await repoTwo.editStuffDatabase(stuff);
return Future.value(true);
case 'secondThing':
initAnotherDependenciesStuff();
List<int> updatedStuff = repoFour.updateStuff();
await repoThree.editStuffDatabase(updatedStuff);
return Future.value(true);
case 'thirdThing':
initDependenciesStuff();
initAnotherDependenciesStuff();
// Another stuffs to do
return Future.value(true);
}
return Future.value(true);
});
}