'List<Data>?' 类型的值不能分配给 'List<Data>' 类型的变量

A value of type 'List<Data>?' can't be assigned to a variable of type 'List<Data>'

我正在尝试使用本教程从测试 API 中获取 Flutter 中的数据 - https://flutterforyou.com/how-to-fetch-data-from-api-and-show-in-flutter-listview/

当我复制代码时 VS Code 抛出这个错误,我不明白,我需要做什么 enter image description here

感谢您的回复,对于虚拟问题、代码示例提前表示抱歉

    Future <List<Data>> fetchData() async {
  
  final response =
      await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
      return jsonResponse.map((data) => Data.fromJson(data)).toList();
  } else {
    throw Exception('Unexpected error occured!');
  }
}

class Data {
  final int userId;
  final int id;
  final String title;

  Data({required this.userId, required this.id, required this.title});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}
class _MyAppState extends State<MyApp> {
  late Future <List<Data>> futureData;

  @override
  void initState() {
    super.initState();
    futureData = fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter API and ListView Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter ListView'),
        ),
        body: Center(
          child: FutureBuilder <List<Data>>(
            future: futureData,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<Data> data = snapshot.data;
                return 
                ListView.builder(
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    height: 75,
                    color: Colors.white,
                    child: Center(child: Text(data[index].title),
                  ),);
                }
              );
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              // By default show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

snapshot.data 可能为 null,你已经知道它不是 null 因为这一行

if (snapshot.hasData)

但是 dart 还不知道...要让它知道,您可以在 data

之后使用 ! 运算符
List<Data> data = snapshot.data!;

List的含义?表示此列表可以为空。

但是 List 意味着这个列表不能为空,但可以为空 [];

解决方案: 让列表成为列表? 这将使您的 List 可以为空,并且您必须在用于执行空检查的任何地方重构您的代码。 为此,将您的构建器方法行编辑为:

List<Data>? data = snapshot.data;

虽然我不推荐这样做,因为您必须在代码中执行手动无效检查,这不是那么漂亮

检查列表是否无效? 我建议使用它,您必须将构建器方法更改为此以进行空检查..

List<Data> data = snapshot.data ?? <Data>[];

这段代码的意思是它会尝试snapshot.data,如果它returns null,它会将<Data>[]分配给数据数组。使它成为一个空数组。

这比可空数组更容易处理(根据我的观点)!

这个错误可以通过像这样更新你的代码来解决,

List<Data> data = snapshot.data ?? <Data>[];

或者像这样,

List<Data> data = snapshot.data!;