我有两个页面:HomePage和DetailsPage,以及关联的GetxControllers。
HomePage:
class HomePage extends GetView<HomeController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('HomePage')),
body: Container(
child: Obx(
() => ListView.builder(
itemCount: controller.task.length,
itemBuilder: (context, index) {
return ListTile(
leading: Text('${index + 1}'),
title: Text(controller.task[index]["name"]),
onTap: () {
Get.to(
DetailsPage(),
arguments: controller.task[index]["name"],
);
},
);
},
),
),
),
);
}
}
HomeController:
:class HomeController extends GetxController {
final TaskRepository repository;
HomeController({@required this.repository}) : assert(repository != null);
final _task = [].obs;
set task(value) => this._task.assignAll(value);
get task => this._task;
onInit() {
super.onInit();
getAllTask();
}
getAllTask() {
repository.getAll().then((value) => task = value);
}
}
正如您所看到的,HomeController 依赖于一个模拟存储库 TaskRepository。
以及我的DetailsPage:
class DetailsPage extends GetView<DetailsController> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
GestureDetector(
onTap: () {
Get.back();
},
child: Row(
children: [
Icon(Icons.arrow_back),
Text('Go Back'),
],
),
),
Expanded(
child: Center(
child: Obx(
() => Text(controller.taskDetail.value),
),
),
),
],
),
);
}
}
DetailsController:
:class DetailsController extends GetxController {
final taskDetail = ''.obs;
@override
void onInit() {
super.onInit();
taskDetail.value = Get.arguments;
}
}
我创建了一个AppDependencies类来初始化依赖项(控制器、存储库、API客户端等):
class AppDependencies {
static Future<void> init() async {
Get.lazyPut(() => HomeController(repository: Get.find()));
Get.lazyPut(() => DetailsController());
Get.lazyPut(() => TaskRepository(apiClient: Get.find()));
Get.lazyPut(() => TaskClient());
}
}
我会通过在main()
中调用AppDependencies.init()
来初始化所有依赖项:
void main() async {
await AppDependencies.init();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
正如第三张图片所示,从详情页返回主页,再次进入详情页会导致异常,提示:
"DetailsController" not found. You need to call "Get.put(DetailsController())" or "Get.lazyPut(()=>DetailsController())"
但我已经在main()
中做过了。我还尝试使用Get.put()
而不是Get.lazyPut()
,但我发现对于Get.put()
,任何其他依赖项的依赖关系必须在相关依赖项之前注册。例如,HomeController依赖于TaskRepository,因此如果像下面这样使用Get.put()
:
Get.put(TaskRepository());
Get.put(HomeController());
这不是我想要的,因为我不想手动跟踪每个元素的先后顺序。我发现这会导致如果有“返回”按钮(几乎每个页面都有),那么会出问题。
我做错了什么?
fenix
? - mufazmifenix
只能与Get.lazyPut()
一起使用,而不能与Get.put()
一起使用。 - mufazmi