gpt4 book ai didi

Flutter/Dart- 方法 'replaceAll' 被调用为 null。如何检查字符串是否存在?

转载 作者:行者123 更新时间:2023-12-03 02:50:17 26 4
gpt4 key购买 nike

我有一个包含 3 个文本字段的表单,供用户插入 3 个标签。在上传到服务器之前,我需要用正则表达式清理它们。问题是,除非用户填写了所有三个文本字段,否则 Android Studio 会抛出以下错误;

E/flutter (13862): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'replaceAll' was called on null.
E/flutter (13862): Receiver: null
E/flutter (13862): Tried calling: replaceAll(RegExp: pattern=[# ] flags=, "")

那么如何在发送前检查每个字段的存在呢?这是代码;

Future<String> uploadTags({String tag1, String tag2, String tag3,}) async {

final serverurl = "http://example.com/example.php";

final String cleantag1 = tag1.replaceAll(RegExp('[# ]'),'');
final String cleantag2 = tag2.replaceAll(RegExp('[# ]'),'');
final String cleantag3 = tag3.replaceAll(RegExp('[# ]'),'');

var request = http.MultipartRequest('POST', Uri.parse(serverurl));

request.fields['tag1'] = cleantag1;
request.fields['tag2'] = cleantag2;
request.fields['tag3'] = cleantag3;

var multiPartFile = await http.MultipartFile.fromPath("audio", filepath, contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
request.send().then((result) async {
http.Response.fromStream(result)
.then((response) {
if (response.statusCode == 200)
{
print('response.body '+response.body);
}
return response.body;
});
});
}

最佳答案

tag1tag2tag3参数值为NULL,

为了确定,在这一行加断点

final String cleantag1 = tag1.replaceAll(RegExp('[# ]'),'');

检查参数值

如果不需要这个值,你可以在变量之后使用 ? :

final String cleantag1 = tag1?.replaceAll(RegExp('[# ]'),'');

如果你想添加一个默认值这样写:

final String cleantag1 = tag1?.replaceAll(RegExp('[# ]'),'')??'defult_value';

关于Flutter/Dart- 方法 'replaceAll' 被调用为 null。如何检查字符串是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63073626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com