Dart flutter遍历List列表时获取迭代的索引

Dart遍历List列表时获取迭代索引,The argument type 'Object?' can't be assigned to the parameter type 'String'

1 min read
By myfreax
Dart flutter遍历List列表时获取迭代的索引

遍历Dart的List列表

main(List<String> args) {
  var servers = [{'title': 'Shenzhen', 'selected': false}, {'title': 'Shanghai', 'selected': true}];
  // ignore: avoid_print
  servers.asMap().map((index, server) => MapEntry(index, print(server['title'])));
}

遍历List的Map元素并获取Map指定Key的value值

import 'package:flutter/material.dart';

main(List<String> args) {
  var servers = [{'title': 'Shenzhen', 'selected': false}, {'title': 'Shanghai', 'selected': true}];
  servers.asMap().map((index, server) => MapEntry(index, ListTile(title: Text(server['title']),)));
}

如果没有定义Map定义类型你将会获得下面的错误,Dart会为你的Map类型定义为List<Map<String, Object>> ,因此需要将Map类型重新定义为List<Map<String, dynamic>>

The argument type 'Object?' can't be assigned to the parameter type 'String'
import 'package:flutter/material.dart';

main(List<String> args) {
  List<Map<String, dynamic>> servers = [
    {'title': 'Shenzhen', 'selected': false},
    {'title': 'Shanghai', 'selected': true}
  ];
  servers.asMap().map((index, server) => MapEntry(
      index,
      ListTile(
        title: Text(server['title']),
      )));
}

Related Articles