widgets.add(_item(key, CITY_NAMES[key])); 报错问题.. 求解

来源:10-3 基于ExpansionTile实现可展开的列表【列表还可以这样做】

Dejan_he

2023-01-12

完整的代码如下:

import 'package:flutter/material.dart';

const Map<String, List<String>> CITY_NAMES = {
  '北京': ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '顺义区'],
  '上海': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '闸北区', '虹口区'],
  '广州': ['越秀', '海珠', '荔湾', '天河', '白云', '黄埔', '南沙', '番禺'],
  '深圳': ['南山', '福田', '罗湖', '盐田', '龙岗', '宝安', '龙华'],
  '杭州': ['上城区', '下城区', '江干区', '拱墅区', '西湖区', '滨江区'],
  '苏州': ['姑苏区', '吴中区', '相城区', '高新区', '虎丘区', '工业园区', '吴江区']
};

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String countString = '';
  String localCount = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('列表展开与收起'),
        ),
        body: Container(
          height: 200,
          child: ListView(
            scrollDirection: Axis.horizontal,
            children: _buildList(),
          ),
        ),
      ),
    );
  }

  List<Widget> _buildList() {
    List<Widget> widgets = [];
    CITY_NAMES.keys.forEach((key) {
      widgets.add(_item(key, CITY_NAMES[key]));
    });
    return widgets;
  }

  Widget _item(String city, List<String> subCities) {
    return ExpansionTile(
      title: Text(
        city,
        style: TextStyle(color: Colors.black54, fontSize: 20),
      ),
      children: subCities.map((subCity) => _buildSub(subCity)).toList(),
    );
  }

  Widget _buildSub(String subCity) {
    return FractionallySizedBox(
        widthFactor: 1,
        child: Container(
          height: 50,
          margin: EdgeInsets.only(bottom: 5),
          decoration: BoxDecoration(color: Colors.lightBlueAccent),
          child: Text(subCity),
        ));
  }
}


报错信息:

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
lib/main.dart:44:40: Error: The argument type 'List<String>?' can't be assigned to the parameter type 'List<String>' because 'List<String>?' is nullable and 'List<String>' isn't.
 - 'List' is from 'dart:core'.
      widgets.add(_item(key, CITY_NAMES[key]));
                                       ^


FAILURE: Build failed with an exception.
写回答

1回答

CrazyCodeBoy

2023-01-13

对照下这块课程源码检查下你的代码实现看是否有出入的地方
https://coding.m.imooc.com/questiondetail.html?qid=134654
0
4
Dejan_he
改为 CITY_NAMES.forEach((key, val){widgets.add(_item(key, val));}); 即可
2023-01-17
共4条回复

Flutter从入门到进阶 实战携程网App 一网打尽核心技术

解锁Flutter开发新姿势,,系统掌握Flutter开发核心技术。

4788 学习 · 3270 问题

查看课程