当前位置:网站首页>Solution of valuenotifier < list < t > > monitoring problem in fluent
Solution of valuenotifier < list < t > > monitoring problem in fluent
2022-06-26 21:44:00 【One leaf floating boat】
1. cause
There is a problem in the development ValueNotifier<List<T>> Monitoring failed , The reason for preliminary confirmation is that the array value has changed, but the address has not changed , And iOS The listening array needs special processing ; A second assignment is required to trigger an address change , Trigger monitoring mechanism ;
2. result : Solve the problem perfectly
The final simple package is as follows :
/// Generic array listener
class ValueNotifierList<T> extends ValueNotifier<List<T>> {
ValueNotifierList(List<T> initValue) : super(initValue);
void add(T item) {
value.add(item);
_copyValue();
}
/// Delete
void remove(int index) {
if (value.length < index) {
return;
}
value.removeAt(index);
_copyValue();
}
/// Delete last
void removeLast() {
if (value.length == 0) {
return;
}
value.removeLast();
_copyValue();
}
void removeAll() {
value.clear();
_copyValue();
}
/// Utilization depth copy Reassign , Trigger monitor
void _copyValue() {
value = [...value];
}
@override
String toString() {
return "${this.runtimeType} common ${value.length} Commodity }";
}
}
3. example:
/// ValueNotifier
static ValueNotifierList valueNotifierList = ValueNotifierList(<OrderModel>[]);
/// ValueNotifier(addListener Invalid Because the array address has not changed , Recommended ValueNotifierList)
static ValueNotifier<List<OrderModel>> valueNotifierListOrigin = ValueNotifier(<OrderModel>[]);
...
@override
void initState() {
super.initState();
valueNotifierList.addListener(update);
valueNotifierListOrigin.addListener(update);
}
@override
void dispose() {
valueNotifierList.removeListener(update);
valueNotifierListOrigin.removeListener(update);
super.dispose();
}
...
void update() {
showSnackBar(SnackBar(content: Text(" Data change monitoring callback , Refresh and rebuild interface ",)), true);
setState(() {});
}
...
void handleActionNum({required ValueNotifierModel e, required int value, required int idx}) {
switch (e.name) {
case "valueNotifierList":
{
final e = OrderModel(name: ' goods ', id: 99, pirce: 1.00);
if (value > 0) {
valueNotifierList.add(e);
} else {
valueNotifierList.removeLast();
}
ddlog(valueNotifierList.toString());
// ddlog("${cartModelOneKey.totalPrice}");
}
break;
case "valueNotifierListOrigin":
{
final e = OrderModel(name: ' goods ', id: 99, pirce: 1.00);
if (value > 0) {
valueNotifierListOrigin.value.add(e);
} else {
valueNotifierListOrigin.value.removeLast();
}
update();/// No listening , It needs to be adjusted manually
ddlog(valueNotifierListOrigin.value.length.toString());
// ddlog("${cartModelOneKey.totalPrice}");
}
break;
default:
break;
}
}
extend :Flutter ValueNotifier asynchronous communication 、ValueListenableBuilder Update data asynchronously
stay Flutter The following schemes can be used for asynchronous communication in :
- Provider
- ValueNotifier
- Stream
- EventBus ( Don't consider using )
- Bloc BLoC
This article describes the use of Navigator Update page A The data of 、ValueListenableBuilder Basic use of 、 Customize ValueNotifier Update local data
1 Preface
In actual project development , One business requirement is page A Enter the page B , On the page B The page needs to be updated after the data changes in A The content in , In fact, the first scheme can consider using then Function callback , The following code list 1-1 Shown , On the page A Open the page in the way of dynamic routing TestBPage, And implement Navigator Of then function ,then The function will be in the TestBPage Callback when the page is closed .
/// Code list 1-1
void openPageFunction(BuildContext context) {
/// Open by dynamic routing
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return TestBPage();
},
),
/// page TestBPage Callback after closing then function
/// The parameter value Is the returned parameter
).then((value) {
if (value != null) {
setState(() {
_message = value;
});
}
});
}
There are three common built-in modules TestBPage closed , It can actively return parameters , The following code detailed list 1-2 Shown :
/// Code detailed list 1-2
OutlineButton buildOutlineButton(BuildContext context) {
return OutlineButton(
child: Text(" Return page A "),
onPressed: () {
String result = "345";
Navigator.of(context).pop(result);
},
);
}
A practical application of this method, such as the details page of an order , After opening the next page for operation , After returning to the current page, you need to refresh the data of the page , This method can be used in this scenario .
Use then Function to achieve data transfer or page refresh , Visible to users , Sometimes the data refresh is slower , Users can feel , Use ValueNotifier Can achieve non sensory refresh .
2 ValueNotifier Basic use of
ValueNotifier Need to combine components ValueListenableBuilder To use .
/// First step Definition ValueNotifier The data type passed here is String
ValueNotifier<String> _testValueNotifier = ValueNotifier<String>('');
/// The second step is to define Monitoring after data change Widget
Widget buildValueListenableBuilder() {
return ValueListenableBuilder(
/// Callback when data changes
builder: (context, value, child) {
return Text(value);
},
/// Monitored data
valueListenable: _testValueNotifier,
child: Text(
' Not logged in ',
style: TextStyle(color: Colors.red),
),
);
}
/// The third step is after the data changes
void testFunction() {
/// Assignment update
_testValueNotifier.value = ' Test data passed ';
}
In the code snippet above , Passing updated data is a String, Of course, in the business development scenario , There will be more customized Model, Directly replace the above String Can .
3 Customize ValueNotifier Partial update
If there is a user data type Model The definition is as follows :
/// In practice, there may be enough variables
class UserInfo {
String name;
int age ;
}
We expect to modify only one of them, such as age The value of an attribute , At this point, you need to decide ValueNotifier , The following code list 1-3 Shown :
/// Code list 1-3
/// Customize ValueNotifier
/// UserInfo Is the data type
class UserNotifier extends ValueNotifier<UserInfo> {
UserNotifier(UserInfo userInfo): super(userInfo);
void setName(String name) {
/// assignment What needs to be noted here is If you don't give ValueNotifier assignment UserInfo Object time
/// value A null pointer exception will occur
value.name =name;
/// Notice Update
notifyListeners();
}
}
And then in use , establish UserNotifier as follows :
/// First step
UserNotifier _testUserNotifier = UserNotifier(UserInfo(name: "", age: 0));structure ValueListenableBuilder
/// The second step Definition
Widget buildUserListenableBuilder() {
return ValueListenableBuilder(
/// Callback when data changes
builder: (context, value, child) {
return Text(" Name is :${value.name} Age is : ${value.age}");
},
/// Monitored data
valueListenable: _testUserNotifier,
);
}
Update when the data changes
void testUserFunction() {
_testUserNotifier.setName(" Li Si ");
} This application scenario is like modifying user data in actual project development , Only one of the attribute data has been modified , You can consider using this method , Of course, there are many details that we don't consider , Directly update all , But all the details come together , It's settled. Why your app experience is always poor .
边栏推荐
- The latest 2022 research review of "continuous learning, CL"
- Sword finger offer 12 Path in matrix
- VB.net类库,获取屏幕内鼠标下的颜色(进阶——3)
- 在哪个平台买股票开户最安全?求分享
- [protobuf] some pits brought by protobuf upgrade
- About appium trample pit: encountered internal error running command: error: cannot verify the signature of (solved)
- Arrête d'être un bébé géant.
- Leetcode question brushing: String 01 (inverted string)
- Kdd2022 𞓜 unified session recommendation system based on knowledge enhancement prompt learning
- 亿级月活全民K歌Feed业务在腾讯云MongoDB中的应用及优化实践
猜你喜欢

基于SSH框架的学生信息管理系统

Cause analysis of 12 MySQL slow queries

Leetcode: hash table 08 (sum of four numbers)

在Flutter中解析复杂的JSON

The source code that everyone can understand (I) the overall architecture of ahooks

How to analyze financial expenses

基于Qt实现的“合成大西瓜”小游戏

Matrix calculator design for beginners of linear algebra based on Qt development
![leetcode:152. Product maximum subarray [consider DP of two dimensions]](/img/c8/af6a4c969affd151a5214723dffb57.png)
leetcode:152. Product maximum subarray [consider DP of two dimensions]

MATLAB与Mysql数据库连接并数据交换(基于ODBC)
随机推荐
ICML2022 | Neurotoxin:联邦学习的持久后门
random_normal_initializer 使用
Treasure and niche cover PBR multi-channel mapping material website sharing
Configure redis master-slave and sentinel sentinel in the centos7 environment (solve the problem that the sentinel does not switch when the master hangs up in the ECS)
线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比
网络爬虫终篇:向10万级网易云用户发送定向消息
Chapter 2 construction of self defined corpus
12个MySQL慢查询的原因分析
leetcode:141. 环形链表【哈希表 + 快慢指针】
中金证券经理给的开户二维码办理股票开户安全吗?我想开个户
Is there any risk in registering and opening an account for stock speculation? Is it safe?
CVPR 2022 | 美团技术团队精选论文解读
【 protobuf 】 quelques puits causés par la mise à niveau de protobuf
2022年,中轻度游戏出海路在何方?
How to enable Hana cloud service on SAP BTP platform
Test comparison of linear model LN, single neural network SNN, deep neural network DNN and CNN
SAP commerce cloud project Spartacus getting started
Implementation of collaborative filtering evolution version neuralcf and tensorflow2
MATLAB and MySQL database connection and data exchange (based on ODBC)
random_ normal_ Initializer uses