类型为“List<Data>?”的值 无法分配给“List<Data>”类型的变量

Art*_*rov 3 async-await dart flutter

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

当我复制代码时,VS Code 抛出此错误,我不明白,我需要做什么, 在此处输入图像描述

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

    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();
            },
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

ema*_*nga 5

列表的含义?意味着这个列表可以为空。

但List表示这个列表不能为空,但可以为空,如[];

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

List<Data>? data = snapshot.data;
Run Code Online (Sandbox Code Playgroud)

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

检查列表是否无效? 我建议使用这个,你必须将你的构建器方法更改为这个以进行空检查。

List<Data> data = snapshot.data ?? <Data>[];
Run Code Online (Sandbox Code Playgroud)

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

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