Search code examples
jsonflutterdartgettype-conversion

How can I convert a JSON String to List<String> in Flutter?


I'm trying to retrieve the content of a table from Oracle Apex to my Flutter app with http.get method, and attribute the values to a class I created. Problem is that 3 of the attributes of this class need to be List<String>, so, when I try to map it, it returns this error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception:
type 'String' is not a subtype of type 'List<String>' in type cast.

This is the JSON:

{
    "items": [
        {
            "id": "1",
            "nome": "Feijão Tropeiro",
            "id_dia_da_semana": "seg",
            "id_categoria": "ga",
            "url_da_imagem": "https://live.staticflickr.com/65535/52180505297_2c23a61620_q.jpg",
            "ingredientes": "vários nadas"
        }
    ],

And this is the class:

// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';

class Meal {
  final String id;
  final String descricao;
  final List<String> ingredients;
  final List<String> idDiaSem;
  final List<String> idCategory;
  final String imageUrl;

  const Meal({
    required this.id,
    required this.descricao,
    required this.ingredients,
    required this.idDiaSem,
    required this.idCategory,
    required this.imageUrl,
  });

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'id': id,
      'nome': descricao,
      'ingredientes': ingredients,
      'id_dia_da_semana': idDiaSem,
      'id_categoria': idCategory,
      'url_da_imagem': imageUrl,
    };
  }

  factory Meal.fromMap(Map<String, dynamic> map) {
    return Meal(
      id: map['id'] as String,
      descricao: map['nome'] as String,
      ingredients: map['ingredientes'] as List<String>,
      idDiaSem: map['id_dia_da_semana'] as List<String>,
      idCategory: map['id_categoria'] as List<String>,
      imageUrl: map['url_da_imagem'] as String,
    );
  }

  String toJson() => json.encode(toMap());

  factory Meal.fromJson(String source) =>
      Meal.fromMap(json.decode(source) as Map<String, dynamic>);
}

How can I fix this error? I've tried to convert it unsuccessfully.


Solution

  • When you have a string you want to parse to a list, there should be a separator. For example, let's suppose this strings:

    // The separator here is a comma with a space, like ', '
    String str1 = 'ingredient1, ingredient2, bread, idunno, etc';
    // The separator here is a simple space, ' '
    String str2 = 'ingredient1 ingredient2 bread idunno etc';
    

    Once you identified the separator in the string, you may want to use the string split method in dart, specifying the separator. For example:

    // Separator is a simple comma with no spaces, ','
    String str1 = 'ingredient1,ingredient2,bread,idunno,etc';
    // Splits the string into array by the separator
    List<String> strList = str1.split(','); 
    // strList = ['ingredient1', 'ingredient2', 'bread', 'idunno', 'etc'];
    

    More information on the split dart method at https://api.dart.dev/stable/2.14.4/dart-core/String/split.html

    EDIT: Example with your code, supposing the property ingredients is a string that represents an array of strings, separated with ",":

    factory Meal.fromMap(Map<String, dynamic> map) {
        return Meal(
          id: map['id'] as String,
          descricao: map['nome'] as String,
          ingredients: (map['ingredientes'] as String).split(','),
          // ...