flutter - 将逗号分隔值添加到类列表
问题描述
我需要在以逗号分隔的列表中添加值。
样本数据:
English,Hindi,French
下面是 List 的类:
class LanguageService {
}
class Language extends Taggable {
final String name;
/// Creates Language
Language({
this.name,
// this.position,
});
@override
List<Object> get props => [name];
/// Converts the class to json string.
String toJson() => ''' {
"name": $name,\n
}''';
//}
String thuJson() => ''' {
"name": $name,
}''';
}
GetTags getTagsFromJson(String str) => GetTags.fromJson(json.decode(str));
class GetTags {
List<Content> content;
bool success;
//String error;
GetTags({
this.content,
this.success,
});
factory GetTags.fromJson(Map<String, dynamic> json) => GetTags(
content: (json["content"] as List).map((x) => Content.fromJson(x)).toList(),
success: json["success"],
);
}
class Content {
String tagname;
Content({
this.tagname,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
tagname: json == null ? 'Empty' : json["tagname"]
);
}
我尝试了拆分,但它给了我错误。
List<Language> _selectedLanguages;
_selectedLanguages = [];
//responseBody['user_lang'] = 'English,Hindi,French' Data looks like this
_selectedLanguages = responseBody['user_lang'].split(', ');
Exception Caught: type 'List<String>' is not a subtype of type 'List<Language>'
也试过了。
_selectedLanguages.add(responseBody['user_lang']);
Exception Caught: type 'String' is not a subtype of type 'Language'
更新
我也尝试过,但出现错误。
List _dbLanguages = responseBody['user_lang'].split(', ');
selectedLanguages = _dbLanguages.map<List<Language>>((item) => Language(item))
A value of type 'Iterable<List<Language>>' can't be assigned to a variable of type 'List<Language>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Language>'.
解决方案
你可以这样做的一种方法是这样的。
List<Language> _selectedLanguages;
_selectedLanguages = (responseBody['user_lang'].split(',') as List<String>).map((text) => Language(name: text)).toList();
推荐阅读
- c# - C# 类 System.Data.SqlClient 无法加载文件或程序集
- python - 如何从同一个包中导入
- amazon-web-services - 如何使用 aws s3 和 Chocolatey 设置提要
- ansible - 使用额外变量设置主机值不适用于我的 Ansible 角色
- intellij-idea - 如何在 IntelliJ IDEA 中启用 -Dkotlinx.coroutines.debug?
- android - android 中是否有标准/推荐的方式(或库)我应该使用 Kotlin 执行 GET、PUT、POST 和 DELETE 请求?
- itext7 - 使用 iText 合并目录中的所有 Pdf 文件
- ios - Xamarin 表单检测屏幕是否处于活动状态和/或设备锁定
- python - UDF 中的 Pyspark 和局部变量
- c# - C#成员变量和传递给方法的参数之间的区别