【问题标题】:A value of type 'List<Data>?' can't be assigned to a variable of type 'List<Data>''List<Data>?' 类型的值不能分配给“List<Data>”类型的变量
【发布时间】:2022-01-08 15:39:03
【问题描述】:

我正在尝试使用本教程从测试 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();
            },
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

  • 更改此:列表?数据 = 快照.data;

标签: flutter dart async-await


【解决方案1】:

列表的含义?表示这个列表可以为空。

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

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

List<Data>? data = snapshot.data;

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

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

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

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

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

【讨论】:

  • 谢谢,帮了大忙!但我还有一个问题,我尝试通过教程访问此链接上的 API - filehost.feelsoftware.com/jsonplaceholder/cars-api.php 我将代码更改为此类 Data { ... factory Data.fromJson(Map json) { return Data (编号:json['cars']['number'],日期:json['cars']['date'],状态:json['cars']['state'],);它抛出 _internallinkhashmap is not a subtype of List
  • 如果您有电报,请用t.me/lightema 联系我,我会在那里为您提供更多帮助
【解决方案2】:

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

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

或者像这样,

List<Data> data = snapshot.data!;

【讨论】:

    【解决方案3】:

    snapshot.data 可能为空,因为这一行,您已经知道它不为空

    if (snapshot.hasData)
    

    但 dart 还不知道...要让它知道,您可以在数据后使用 ! 运算符

    List<Data> data = snapshot.data!;
    

    【讨论】:

    • 既然可能返回null,snapshot.hasData中的数据不会是null吗?
    • @emanuelsanga 抱歉,我不确定我是否理解您的问题,snapshot.hasData 只有在snapshot.data 不为空 时才会为真,即使未来已经完成。跨度>
    • 我明白了,我要问的是,考虑到传递的函数可以为空,颤振不会将 null 视为数据吗?
    • 不,正如您在documentation 中看到的那样,只要snapshot.hasData 为真,数据将永远为空,即使未来已完成且功能为可以为空
    • 感谢@hmoss,我错过了一些东西
    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2021-08-05
    • 2020-10-24
    相关资源
    最近更新 更多