Flutter响应式计算值管理插件computed_value_notifier的使用
Flutter响应式计算值管理插件computed_value_notifier的使用
使用
ComputedValueNotifier
可以用来根据另一个 Listenable
或多个 Listenable
的数据派生出一个值。当提供的 listenable
通知监听器其值已更改时,该值将被重新计算。
简单示例
final email = ValueNotifier<String>('a');
// 使用一个(hacky)验证器来确定电子邮件是否有效。
final emailValid = ComputedValueNotifier(
email,
() => email.value.contains('@'),
);
// 提供给 ComputedValueNotifier 的函数会立即执行,并且计算出的值可以同步获取。
print(emailValid.value); // 打印 'false'。
// 当 email ValueNotifier 改变时,函数会被再次执行!
email.value = 'a@b.com';
print(emailValid.value); // 打印 'true'。
示例代码
以下是完整的示例代码,展示了如何在实际应用中使用 ComputedValueNotifier
。
import 'package:flutter/material.dart';
// 定义一个表单视图模型类,用于管理表单字段的状态。
class FormViewModel {
final email = ValueNotifier<String>('');
final password = ValueNotifier<String>('');
// 使用 ComputedValueNotifier 来管理登录按钮是否可点击的状态。
final canLogin = ComputedValueNotifier(
[email, password],
() => email.value.isNotEmpty && password.value.isNotEmpty,
);
// 在组件销毁时清理资源。
void dispose() {
email.dispose();
password.dispose();
}
}
void main(List<String> args) {
runApp(const ExampleApp());
}
class ExampleApp extends StatelessWidget {
const ExampleApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
[@override](/user/override)
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
late final FormViewModel formViewModel;
[@override](/user/override)
void initState() {
super.initState();
formViewModel = FormViewModel();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Computed Value Notifier Example')),
body: Center(
child: FractionallySizedBox(
widthFactor: 0.8,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
decoration: const InputDecoration(hintText: 'Email'),
onChanged: (newValue) => formViewModel.email.value = newValue,
),
const SizedBox(height: 10),
TextField(
obscureText: true,
decoration: const InputDecoration(hintText: 'Password'),
onChanged: (newValue) =>
formViewModel.password.value = newValue,
),
const SizedBox(height: 10),
ValueListenableBuilder<bool>(
valueListenable: formViewModel.canLogin,
child: const Text('Log In'),
builder: (context, canLogin, child) {
return ElevatedButton(
onPressed: canLogin ? () {} : null,
child: child,
);
},
),
],
),
),
),
);
}
[@override](/user/override)
void dispose() {
formViewModel.dispose();
super.dispose();
}
}
更多关于Flutter响应式计算值管理插件computed_value_notifier的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复