简体   繁体   中英

Error when pasting json code converted into dart in flutter project

I am following a tutorial where I'm supposed to convert a json code(provided by the instructor) to dart code using online converter, but when I paste the code in my project it gives number of errors errors which I am not able to fix. I'm still a beginner please help.

class ExerciseHub {
  List<Exercises> exercises;

  ExerciseHub({this.exercises});

  ExerciseHub.fromJson(Map<String, dynamic> json) {
    if (json['exercises'] != null) {
      exercises = new List<Exercises>();
      json['exercises'].forEach((v) {
        exercises.add(new Exercises.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.exercises != null) {
      data['exercises'] = this.exercises.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Exercises {
  String id;
  String title;
  String thumbnail;
  String gif;
  String seconds;

  Exercises({this.id, this.title, this.thumbnail, this.gif, this.seconds});

  Exercises.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    title = json['title'];
    thumbnail = json['thumbnail'];
    gif = json['gif'];
    seconds = json['seconds'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['title'] = this.title;
    data['thumbnail'] = this.thumbnail;
    data['gif'] = this.gif;
    data['seconds'] = this.seconds;
    return data;
  }
}

Following is the screenshot of errors I got [1]: https://i.stack.imgur.com/EuHUd.png

I assume you're using a recent version of Flutter (2.2 or higher) which comes with Dart null-safety by default. Unfortunately, the code sample you have isn't written in null-safe Dart. Maybe the online converter doesn't support it?

The Dart version required for your project is defined in pubspec.yaml . Starting from Dart 2.12, null-safety is applied.

environment:
  sdk: '>=2.12.0 <3.0.0'

Check if the online converter supports Dart 2.12 or higher or else you can add the following comment to the top of your file to change the Dart version of that specific file:

// @dart=2.9
class ExerciseHub {
  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM