当前位置:网站首页>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 .
边栏推荐
- AI智能抠图工具--头发丝都可见
- Leetcode question brushing: String 06 (implement strstr())
- leetcode:152. 乘积最大子数组【考虑两个维度的dp】
- 关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)
- 在哪个平台买股票开户最安全?求分享
- 传纸条【动态规划】
- 诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东
- lotus configurations
- Chapter 2 construction of self defined corpus
- Android IO, a first-line Internet manufacturer, is a collection of real questions for senior Android interviews
猜你喜欢

俞敏洪:新东方并不存在倒下再翻身,摧毁又雄起的逆转

Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders

Student information management system based on SSH Framework

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

Redis + guava local cache API combination, performance burst!

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

API管理之利剑 -- Eolink

Dynamic parameter association using postman

The source code that everyone can understand (I) the overall architecture of ahooks
![[solution] sword finger offer 15 Number of 1 in binary (C language)](/img/ab/149775ae8ed94464efdf6921c1022a.png)
[solution] sword finger offer 15 Number of 1 in binary (C language)
随机推荐
360 mobile assistant is the first to access the app signature service system to help distribute privacy and security
基于SSH框架的学生信息管理系统
How to enable Hana cloud service on SAP BTP platform
Homebrew installation in MacOS environment [email protected]
Final part of web crawler: send directional messages to 100000 Netease cloud users
诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东
DAST 黑盒漏洞扫描器 第五篇:漏洞扫描引擎与服务能力
大龄程序员的一些出路
12个MySQL慢查询的原因分析
Matrix calculator design for beginners of linear algebra based on Qt development
Convolutional neural network (CNN) explanation and tensorflow2 code implementation
Looking back at the moon
Sword finger offer 12 Path in matrix
VB.net类库,获取屏幕内鼠标下的颜色(进阶——3)
ICML2022 | Neurotoxin:联邦学习的持久后门
MacOS環境下使用HomeBrew安裝[email protected]
Leetcode question brushing: String 03 (Sword finger offer 05. replace space)
API管理之利剑 -- Eolink
Android IO, a first-line Internet manufacturer, is a collection of real questions for senior Android interviews
Redis + guava local cache API combination, performance burst!