当前位置:网站首页>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 .
边栏推荐
- Leetcode(763)——划分字母区间
- SAP Spartacus 中的依赖注入 Dependency Injection 介绍
- The latest 2022 research review of "continuous learning, CL"
- 网络爬虫终篇:向10万级网易云用户发送定向消息
- PostgreSQL notes
- Can compass open an account for stock trading? Is it safe?
- 这个算BUG吗?乱填的字母是否可以关闭
- Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
- Sword finger offer 12 Path in matrix
- leetcode:6107. 不同骰子序列的数目【dp六个状态 + dfs记忆化】
猜你喜欢

Many gravel 3D material mapping materials can be obtained with one click

基于启发式搜索的一字棋

KDD2022 | 基于知识增强提示学习的统一会话推荐系统

Y48. Chapter III kubernetes from introduction to mastery -- pod status and probe (21)
![leetcode:152. Product maximum subarray [consider DP of two dimensions]](/img/c8/af6a4c969affd151a5214723dffb57.png)
leetcode:152. Product maximum subarray [consider DP of two dimensions]

Redis + Guava 本地缓存 API 组合,性能炸裂!

会计要素包括哪些内容

关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)

【题解】剑指 Offer 15. 二进制中1的个数(C语言)

The postgraduate entrance examination in these areas is crazy! Which area has the largest number of candidates?
随机推荐
Background search, how to find the website background
模块五作业
十大券商注册开户有没有什么风险?安全吗?
Is there any risk for flush to register and open an account? Is it safe?
基于Qt实现的“合成大西瓜”小游戏
Dynamic parameter association using postman
leetcode:152. 乘积最大子数组【考虑两个维度的dp】
基于SSH框架的学生信息管理系统
Godson China Science and technology innovation board is listed: the market value is 35.7 billion yuan, becoming the first share of domestic CPU
Introduction of classic wide & deep model and implementation of tensorflow 2 code
MacOS环境下使用HomeBrew安装[email protected]
AI智能抠图工具--头发丝都可见
龙芯中科科创板上市:市值357亿 成国产CPU第一股
Listing of maolaiguang discipline on the Innovation Board: it is planned to raise 400million yuan. Fanyi and fanhao brothers are the actual controllers
请问CMS里UniAPP版本中的&ldquo;自定义表单列表如何去掉?
DAST 黑盒漏洞扫描器 第五篇:漏洞扫描引擎与服务能力
Can compass open an account for stock trading? Is it safe?
SAP commerce cloud project Spartacus getting started
Yolov6: un cadre de détection de cibles rapide et précis est Open Source
random_ normal_ Initializer uses