这是一个示例,说明如何使用 GetX 的 observables 动态更新表单字段和提交按钮。
我没有声称这是最佳做法。我敢肯定有更好的方法来完成同样的事情。但是玩弄如何使用 GetX 来执行验证是很有趣的。
表单+Obx
基于 Observable 值变化重建的两个感兴趣的小部件:
- 文本表单字段
- InputDecoration 的
errorText 更改并重新构建此小部件
-
onChanged: fx.usernameChanged 不会导致重建。当表单字段输入发生变化时,这将调用控制器 usernameChanged(String val) 中的一个函数。
- 它只是将
username observable 更新为一个新值。
- 可以写成:
onChanged: (val) => fx.username.value = val
- ElevatedButton(“提交”按钮)
-
onPressed 函数可以在 null 和函数之间切换
-
null 禁用按钮(在 Flutter 中这样做的唯一方法)
- 这里有一个函数可以启用按钮
class FormObxPage extends StatelessWidget {
const FormObxPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
FormX fx = Get.put(FormX()); // controller
return Scaffold(
appBar: AppBar(
title: const Text('Form Validation'),
),
body: SafeArea(
child: Container(
alignment: Alignment.center,
margin: const EdgeInsets.symmetric(horizontal: 5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Obx(
() {
print('rebuild TextFormField ${fx.errorText.value}');
return TextFormField(
onChanged: fx.usernameChanged, // controller func
decoration: InputDecoration(
labelText: 'Username',
errorText: fx.errorText.value // obs
)
);
},
),
Obx(
() => ElevatedButton(
child: const Text('Submit'),
onPressed: fx.submitFunc.value, // obs
),
)
],
),
),
),
);
}
}
GetX 控制器
下面的解释/细分
class FormX extends GetxController {
RxString username = RxString('');
RxnString errorText = RxnString(null);
Rxn<Function()> submitFunc = Rxn<Function()>(null);
@override
void onInit() {
super.onInit();
debounce<String>(username, validations, time: const Duration(milliseconds: 500));
}
void validations(String val) async {
errorText.value = null; // reset validation errors to nothing
submitFunc.value = null; // disable submit while validating
if (val.isNotEmpty) {
if (lengthOK(val) && await available(val)) {
print('All validations passed, enable submit btn...');
submitFunc.value = submitFunction();
errorText.value = null;
}
}
}
bool lengthOK(String val, {int minLen = 5}) {
if (val.length < minLen) {
errorText.value = 'min. 5 chars';
return false;
}
return true;
}
Future<bool> available(String val) async {
print('Query availability of: $val');
await Future.delayed(
const Duration(seconds: 1),
() => print('Available query returned')
);
if (val == "Sylvester") {
errorText.value = 'Name Taken';
return false;
}
return true;
}
void usernameChanged(String val) {
username.value = val;
}
Future<bool> Function() submitFunction() {
return () async {
print('Make database call to create ${username.value} account');
await Future.delayed(const Duration(seconds: 1), () => print('User account created'));
return true;
};
}
}
可观察的
从三个 observables 开始...
RxString username = RxString('');
RxnString errorText = RxnString(null);
Rxn<Function()> submitFunc = Rxn<Function()>(null);
username 将保存上次输入到 TextFormField 的内容。
errorText 以null 初始值进行实例化,因此用户名字段一开始就不是“无效”的。如果 not 为空(甚至是空字符串),TextFormField 将被渲染为红色以表示无效输入。当字段中有无效输入时,我们将显示错误消息。 (例如min. 5 chars:)
submitFunc 是持有提交按钮函数或null 的 observable,因为 Dart 中的函数实际上是对象,这很好。 null 值初始分配将禁用按钮。
onInit
debounce 工作器在更改 username 可观察端 500 毫秒后调用 validations 函数。
validations 将接收 username.value 作为其参数。
More on workers.
验证
在 validations 函数中,我们放置了我们想要运行的任何类型的验证:最小长度、错误字符、已使用的名称、由于童年欺凌而我们个人不喜欢的名称等。
为了增加真实感,available() 函数是async。通常这会查询数据库以检查用户名的可用性,因此在此示例中,在返回此验证检查之前存在 1 秒的虚假延迟。
submitFunction() 返回一个函数,当我们确信表单具有有效输入并允许用户继续时,该函数将替换 submitFunc observable 中的空值。
更现实一点,我们会尝试。期望提交按钮函数有一些返回值,所以我们可以让按钮函数返回一个未来的布尔值:
Future<bool> Function() submitFunction() {
return () async {
print('Make database call to create ${username.value} account');
await Future.delayed(Duration(seconds: 1), () => print('User account created'));
return true;
};
}