当前位置:网站首页>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 .
边栏推荐
- 「连续学习Continual learning, CL」最新2022研究综述
- In 2022, where will the medium and light-weight games go?
- Leetcode: String 04 (reverse the words in the string)
- Background search, how to find the website background
- [leetcode]- linked list-2
- [Shandong University] information sharing for the first and second examinations of postgraduate entrance examination
- KDD2022 | 基于知识增强提示学习的统一会话推荐系统
- Cause analysis of 12 MySQL slow queries
- Yonghui released the data of Lantern Festival: the sales of Tangyuan increased significantly, and several people's livelihood products increased by more than 150%
- Leetcode question brushing: String 06 (implement strstr())
猜你喜欢

线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比
![[LeetCode]-链表-2](/img/f7/9d4b01285fd6f7fa9f3431985111b0.png)
[LeetCode]-链表-2

leetcode:6103. 从树中删除边的最小分数【dfs + 联通分量 + 子图的值记录】

QT based "synthetic watermelon" game

茂莱光学科创板上市:拟募资4亿 范一与范浩兄弟为实控人

Leetcode question brushing: String 05 (Sword finger offer 58 - ii. left rotation string)

第2章 构建自定义语料库
![leetcode:152. Product maximum subarray [consider DP of two dimensions]](/img/c8/af6a4c969affd151a5214723dffb57.png)
leetcode:152. Product maximum subarray [consider DP of two dimensions]

龙芯中科科创板上市:市值357亿 成国产CPU第一股

leetcode:710. 黑名单中的随机数【映射思维】
随机推荐
如何在 SAP BTP 平台上启用 HANA Cloud 服务
What is the “ How to remove a custom form list?
How to create an OData service with the graphical modeler on the sap BTP platform
[Shandong University] information sharing for the first and second examinations of postgraduate entrance examination
聊聊我的远程工作体验 | 社区征文
网易云信正式加入中国医学装备协会智慧医院分会,为全国智慧医院建设加速...
The latest 2022 research review of "continuous learning, CL"
如何用 SAP BTP 平台上的图形建模器创建一个 OData 服务
Sword finger offer II 098 Number of paths / Sword finger offer II 099 Sum of minimum paths
Leetcode question brushing: String 01 (inverted string)
Test comparison of linear model LN, single neural network SNN, deep neural network DNN and CNN
360 mobile assistant is the first to access the app signature service system to help distribute privacy and security
KDD2022 | 基于知识增强提示学习的统一会话推荐系统
Many gravel 3D material mapping materials can be obtained with one click
传纸条【动态规划】
DAST 黑盒漏洞扫描器 第五篇:漏洞扫描引擎与服务能力
Leetcode(763)——划分字母区间
What are the accounting elements
Y48. Chapter III kubernetes from introduction to mastery -- pod status and probe (21)
AI intelligent matting tool - hair can be seen