Dart代码分析:理解变量totalNum在异步请求中的变化
Dart代码分析:理解变量totalNum在异步请求中的变化
以下代码片段展示了在Dart中使用异步请求函数request()时,变量totalNum的值变化情况。
var totalNum = 0;
Future request() async {
String myID = await OpenIM.iMManager.getLoginUserID();
var list;
list = await Apis.cipherTextRetrieval2(
sendTime: dateTime.toString().replaceAll(new RegExp(r'[^0-9]'), '').substring(0, 8),
friendID: uid!,
userID: myID,
messageType: int.parse(messageType!) == MessageType.text ? null : messageType,
total: totalNum,
offset: offset,
limit: limit
);
}
class Apis {
static Future<List> cipherTextRetrieval2({
required String sendTime,
required String friendID,
required String userID,
required String? messageType,
int? total,
int? offset = 0,
int? limit = 10
}) async {
total = 10;
}
}
分析:
在上述代码中,request()方法中定义了变量totalNum,初始值为0。在调用Apis.cipherTextRetrieval2()方法时,将totalNum作为参数传递给total参数。
然而,在Apis.cipherTextRetrieval2()方法内部,对total参数进行了赋值操作:total = 10;。该赋值操作仅在Apis.cipherTextRetrieval2()方法内部生效,并不会改变request()方法中的totalNum的值。
因此,在request()方法执行结束后,totalNum的值依然保持为0,不会因为Apis.cipherTextRetrieval2()方法中的赋值操作而发生改变。
总结:
在异步请求中,函数参数的传递是值传递,即传递的是参数的副本,对副本的修改不会影响原参数的值。因此,Apis.cipherTextRetrieval2()方法中对total参数的赋值操作不会影响request()方法中的totalNum的值。
如果需要在异步请求中修改外部变量的值,可以使用FutureBuilder组件或其他异步操作机制。
原文地址: https://www.cveoy.top/t/topic/nyFy 著作权归作者所有。请勿转载和采集!