参数类型“对象?”无法分配给参数类型“String”。?

问题描述 投票:0回答:2

我的模型颤动项目有问题.. 我收到错误:

参数类型“对象?”无法分配给参数类型 ‘字符串’。

参数类型“对象?”无法分配给参数类型 “国际”。

参数类型“对象?”无法分配给参数类型 ‘字符串’。

class Category {
  final String name;
  final int numOfCourses;
  final String image;

  Category(this.name, this.numOfCourses, this.image);
}

List<Category> categories = categoriesData
    .map((item) => Category(item['name'], item['courses'], item['image']))
    .toList();

var categoriesData = [
  {"name": "Marketing", 'courses': 17, 'image': "assets/images/marketing.png"},
  {"name": "UX Design", 'courses': 25, 'image': "assets/images/ux_design.png"},
  {
    "name": "Photography",
    'courses': 13,
    'image': "assets/images/photography.png"
  },
  {"name": "Business", 'courses': 17, 'image': "assets/images/business.png"},
];

这部分有错误

(item['name'], item['courses'], item['image'])

感谢您的回答..

list flutter dart model
2个回答
1
投票

Dart 不知道

categoriesData['name']
categoriesData['courses']
categoriesData['image']
应该是什么,要告诉它,你可以使用
as
关键字:

categories = categoriesData
    .map((item) => Category(item['name'] as String, item['courses'] as int, item['image'] as String))
    .toList();

0
投票

您还可以使用 flutter_helper_utils 包中的转换助手,因为关键字

as
并不总是有效,尤其是与
List
Map
一起使用,以及当您尝试在双数据上使用它但使用
as int
时。 但在此之前,我们需要使用可序列化的方法清理你的类 这是您的课程的清理版本:

class Category {
  final String name;
  final int numOfCourses;
  final String image;

  Category(this.name, this.numOfCourses, this.image);

  factory Category.fromJson(Map<String, dynamic> map) {
    return Category(
      toString1(map['name']),
      toInt(map['courses']),
      toString1(map['image']),
    );
  }

  static List<Category> fromList(List<dynamic> list) {
    return list.map((e) => Category.fromJson(toMap(e))).toList();
  }
}

然后你可以像这样使用你的类:

final categories = Category.fromList(categoriesData);
// or to get single category from map you can.
final category = Category.fromJson(mapData);
© www.soinside.com 2019 - 2024. All rights reserved.