Roxx
Roxx

Reputation: 3986

Add comma separated value to class list

I need to add the value in the list which is comma separated.

Sample data:

English,Hindi,French

Below is the class of 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"]
    );
    
}

I tried split but it is giving me error.

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

Also tried.

_selectedLanguages.add(responseBody['user_lang']);
Exception Caught: type 'String' is not a subtype of type 'Language'

Update

I tried this too but getting error.

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

Upvotes: 5

Views: 4108

Answers (3)

Quick learner
Quick learner

Reputation: 11457

Try this

String finalStringValue = list_here.map((item) => item).join(', ');

Upvotes: 1

Jigar Patel
Jigar Patel

Reputation: 5423

One way you can do this is like this.

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

Upvotes: 2

Pablo
Pablo

Reputation: 6048

Dart has a very good type checking system and I think your problem is an obvious one based on the error message. You must convert your list of String into a list of Language. I don't recall the syntax from the top of my head but I think you should be able to convert your list of String with .map<List<Language>>((item) => Language(item))

Upvotes: 1

Related Questions