gpt4 book ai didi

flutter - 将逗号分隔值添加到类列表

转载 作者:行者123 更新时间:2023-12-03 02:59:09 28 4
gpt4 key购买 nike

我需要在逗号分隔的列表中添加值。

示例数据:

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();

关于flutter - 将逗号分隔值添加到类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63779722/

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