简体   繁体   English

在flutter项目中粘贴转换成dart的json代码时出错

[英]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.我正在学习一个教程,我应该使用在线转换器将 json 代码(由讲师提供)转换为 dart 代码,但是当我将代码粘贴到我的项目中时,它给出了我无法修复的错误数量. 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以下是我得到的错误截图[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.我假设您使用的是最新版本的 Flutter(2.2 或更高版本),默认情况下它带有 Dart 空安全。 Unfortunately, the code sample you have isn't written in null-safe Dart.不幸的是,您拥有的代码示例不是用空安全 Dart 编写的。 Maybe the online converter doesn't support it?也许在线转换器不支持它?

The Dart version required for your project is defined in pubspec.yaml .项目所需的 Dart 版本在pubspec.yaml定义。 Starting from Dart 2.12, null-safety is applied.从 Dart 2.12 开始,应用了空安全。

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.12 或更高版本,否则您可以在文件顶部添加以下注释以更改该特定文件的 Dart 版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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