flutter 如何将Map加入Map列表?

7kqas0il  于 2023-01-27  发布在  Flutter
关注(0)|答案(3)|浏览(171)

让我们假设我有这个Map列表:

List values = [
  {
    'icon': FontAwesomeIcons.book,
    'title': 'A',
    'books': [
      {'author': 'Max', 'age': 30},
      {'author': 'Dani', 'age': 45}
    ]
  },
  {
    'icon': FontAwesomeIcons.book,
    'title': 'B',
    'books': [],
  }
];

如何检查这本书是否存在的标题'A' {'author': 'Steve', 'age': 28},,如果它不存在,如何添加它。
编辑:
我想达到的结果是:

List values = [
      {
        'icon': FontAwesomeIcons.book,
        'title': 'A',
        'books': [
          {'author': 'Max', 'age': 30},
          {'author': 'Dani', 'age': 45},
          {'author': 'Steve', 'age': 28} 
        ]
      },
      {
        'icon': FontAwesomeIcons.book,
        'title': 'B',
        'books': [],
      }
    ];
o4hqfura

o4hqfura1#

我强烈推荐使用数据模型.它会使你的工作更容易.

class DataModel {
  String? title;
  List<Books>? books;

  DataModel({this.title, this.books});

  DataModel.fromJson(Map<String, dynamic> json) {
    title = json['title'];
    if (json['books'] != null) {
      books = <Books>[];
      json['books'].forEach((v) {
        books!.add(new Books.fromJson(v));
      });
    }
  }

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

class Books {
  String? author;
  int? age;

  Books({this.author, this.age});

  Books.fromJson(Map<String, dynamic> json) {
    author = json['author'];
    age = json['age'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['author'] = this.author;
    data['age'] = this.age;
    return data;
  }
}

使用此模型时,您可以轻松转换和编辑数据:

List<DataModel> list = [];
  for(final item in values){
    list.add(DataModel.fromJson(item));
  }
  
  final bookExcists = list.any((book) => book.title == 'A');
  
  if(bookExcists){
    list.firstWhere((book) => book.title == 'A').books?.add(Books.fromJson({'author': 'Steve', 'age': 28}));
  }
  
  
  for(final item in list){
    print(item.toJson());
  }
42fyovps

42fyovps2#

您可以使用.firstWhere查找项目,例如

final result = values.firstWhere(
  (element) => element["title"] == "A",
  orElse: () => null,
);

print(result);

if (result == null) {
  values.add({
    'icon': FontAwesomeIcons.book,
    'title': 'A',
    'books': [
      {'author': 'Max', 'age': 30},
      {'author': 'Dani', 'age': 45}
    ]
  });
}

print(values);
mzmfm0qo

mzmfm0qo3#

// Check by title
  final bookExcists = values.any((book) => book['title'] == 'A');
  
  if(!bookExcists){
  values.add({
    'icon': FontAwesomeIcons.book,
    'title': 'A',
    'books': [
      {'author': 'Max', 'age': 30},
      {'author': 'Dani', 'age': 45}
    ]
  });
  }
  
  print(values);

相关问题