【发布时间】:2021-12-20 10:22:17
【问题描述】:
我正在尝试从 Provider 转移到 GetX,但我对 GetX.find() 的工作方式感到困惑。
我们有一个restaurant 应用程序和几个tables。下面是我的旧Provider 代码的缩小视图,仅显示staff 表和VIP 表。您单击“就座”按钮将桌子标记为就座。:
Widget build(BuildContext context) {
return MaterialApp(
title: 'Restaurant',
home: Column(children: [
ChangeNotifierProvider<Table>( //Provider
create: (_) => Table("Staff"), //create controller
child: Builder(builder: (context) {
return Column(children: [
Text("Staff seated: ${context.watch<Table>().seated}"), //consume changes
ElevatedButton(
child: const Text("Seat Staff"),
onPressed: () {
context.read<Table>().toggleSeated(); //call controller
}),
]);
}),
),
ChangeNotifierProvider<Table>(. //Provider
create: (_) => Table("VIP"), //create controller
child: Builder(
builder: (context) {
return Column(children: [
Text("VIP seated: ${context.watch<Table>().seated}"), //consume changes
ElevatedButton(
child: const Text("Seat VIP"),
onPressed: () {
context.read<Table>().toggleSeated(); //call controller
}),
]);
},
)),
]),
);
}
}
和相关的缩小控制器:
class Table extends ChangeNotifier {
final String name;
int chairs = 0;
bool seated = false;
Table(this.name);
toggleSeated() {
seated = !seated;
notifyListeners(); //notify providers
}
}
现在这里是GetX 代码(编译良好),但我尝试了t.toggle 和Get.find<Table>().toggle,这两个函数同时切换两个表。在旧代码中,他们分别切换了表格:
Widget build(BuildContext context) {
return MaterialApp(
title: 'Restaurant',
home: Column(
children: [
GetBuilder( //GetX
init: Table("Staff"), //create controller
builder: (Table t) {
return Column(children: [
Text("Staff seated: ${t.seated}"), //consume changes
ElevatedButton(
child: const Text("Seat Staff"),
onPressed: () {
//I've tried Get.find here
Get.find<Table>().toggleSeated(); //call controller
},
),
]);
},
),
GetBuilder(. //GetX
init: Table("VIP"), //create controller
builder: (Table t) {
return Column(children: [
Text("VIP seated: ${t.seated}"), //consume changes
ElevatedButton(
child: const Text("Seat VIP"),
onPressed: () {
//I've also tried directly using the controller
t.toggleSeated(); //call controller
},
),
]);
},
),
],
));
}
和相关的缩小控制器:
class Table extends GetxController {
final String name;
int chairs = 0;
bool seated = false;
Table(this.name);
toggleSeated() {
seated = !seated;
update(); //notify GetX
}
}
在Provider 版本中,我可以单独与表格交互,但在GetX 版本中,无论我使用Get.find<Table>() 还是直接使用控制器的t.toggle,按钮似乎都对所有表格起作用。
【问题讨论】:
-
这是一个非常好的问题。我想原因可能是这里的内部工作你同时访问一个实例,因此一次切换。我在 getx 中探索了多个实例的 tag 属性,但它不是动态的,布尔映射可能是一种解决方案。但我仍在查看内部代码。
标签: flutter flutter-provider flutter-getx