首页 > 解决方案 > 将逗号分隔值添加到类列表

问题描述

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

样本数据:

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>'.

标签: flutterdart

解决方案


你可以这样做的一种方法是这样的。

List<Language> _selectedLanguages;
_selectedLanguages = (responseBody['user_lang'].split(',') as List<String>).map((text) => Language(name: text)).toList();

推荐阅读