当前位置:网站首页>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 .
边栏推荐
- How SAP Spartacus default routing configuration works
- 俞敏洪:新东方并不存在倒下再翻身,摧毁又雄起的逆转
- 关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)
- 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)
- VB.net类库,获取屏幕内鼠标下的颜色(进阶——3)
- Y48. Chapter III kubernetes from introduction to mastery -- pod status and probe (21)
- The importance of using fonts correctly in DataWindow
- DLA模型(分类模型+改进版分割模型) + 可变形卷积
- Treasure and niche cover PBR multi-channel mapping material website sharing
- 指南针能开户炒股吗?安全吗?
猜你喜欢

网易云信正式加入中国医学装备协会智慧医院分会,为全国智慧医院建设加速...

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

leetcode:6107. 不同骰子序列的数目【dp六个状态 + dfs记忆化】

The postgraduate entrance examination in these areas is crazy! Which area has the largest number of candidates?

Treasure and niche cover PBR multi-channel mapping material website sharing

基于Qt实现的“合成大西瓜”小游戏
![leetcode:1567. 乘积为正数的最长子数组长度【dp[i]表示以i结尾的最大长度】](/img/a4/c5c31de7a0a3b34a188bfec0b5d184.png)
leetcode:1567. 乘积为正数的最长子数组长度【dp[i]表示以i结尾的最大长度】

Looking back at the moon

Listing of maolaiguang discipline on the Innovation Board: it is planned to raise 400million yuan. Fanyi and fanhao brothers are the actual controllers

Matrix calculator design for beginners of linear algebra based on Qt development
随机推荐
360手机助手首家接入APP签名服务系统 助力隐私安全分发
Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
Usage of MGrid in numpy
Cause analysis of 12 MySQL slow queries
The importance of using fonts correctly in DataWindow
CVPR 2022 | 美团技术团队精选论文解读
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)
Icml2022 | neurotoxin: a lasting back door to federal learning
俞敏洪:新东方并不存在倒下再翻身,摧毁又雄起的逆转
中金证券经理给的开户二维码办理股票开户安全吗?我想开个户
MATLAB and MySQL database connection and data exchange (based on ODBC)
leetcode:1567. 乘积为正数的最长子数组长度【dp[i]表示以i结尾的最大长度】
线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比
The latest 2022 research review of "continuous learning, CL"
numpy中mgrid的用法
How to enable Hana cloud service on SAP BTP platform
SAP Commerce Cloud 项目 Spartacus 入门
宝藏又小众的覆盖物PBR多通道贴图素材网站分享
Web crawler 2: crawl the user ID and home page address of Netease cloud music reviews
Is it safe for CICC fortune to open an account? I want to open an account to speculate in stocks.