Get variable value from an external class

Viewed 46

I have an external complex class :

class SentenceList {
  final List<Sentence> sentences;
  SentenceList({
    this.sentences,
  });
  factory SentenceList.fromJson(List<dynamic> parsedJson) {
    List<Sentence> sentences = [];
    sentences = parsedJson.map((i) => Sentence.fromJson(i)).toList();
    return new SentenceList(sentences: sentences);
  }
}

class Sentence {
  final String idName;
  final String name;
  final String assets;
  final List<String> sentence;

  Sentence({this.idName, this.name, this.assets, this.sentence});

  factory Sentence.fromJson(Map<String, dynamic> parsedJson) {
    var sentenceFromJson = parsedJson['sentence'];
    //print(sentenceFromJson.runtimeType);
    List<String> sentenceList = sentenceFromJson.cast<String>();

    return Sentence(
      idName: parsedJson["idName"].toString(),
      name: parsedJson["name"],
      assets: parsedJson["assets"],
      sentence: sentenceList,
    );
  }
}

In which i want to get the values from "sentences" variable , Therefore i do that (in the main.dart).

    SentenceList data = SentenceList() ;
    debugPrint('myName : ${data.sentences[0].idName}');

But i have an error , and don't know where is my mistake. Thank you for your help

1 Answers

You should provide a list of sentences to the SentenceList class because the sentences are not initialised currently.

Sentence sentence = Sentence(
  idName: 'Test',
  name: 'The first sentence',
  assets: 'None',
  sentence: ['The', 'cow', 'is', 'brown'],
);

SentenceList data = SentenceList(sentences: [sentence]);
Related