【问题标题】:Flutter dynamic list, not-null validationFlutter 动态列表,非空验证
【发布时间】:2021-08-22 01:28:40
【问题描述】:

我一直在尝试创建一个 Flutter Widget 列表以在滑块中使用它们。
我正在从 JSON 文件中获取数据,并将其作为 Future 传递给 FutureBuilder
但是,当尝试构建我的应用程序时,会弹出错误消息:

错误:不能在“列表?”上调用运算符“[]”因为它可能为空。 'List' 来自 'dart:core'。

我尝试使用“初始数据”验证它或检查它是否不为空,但它们似乎不起作用。
是否有一些不错的解决方案可以像 ListView.builder 中的 ItemBuilder 那样获取小部件列表?
注意:当我使用静态数据构建应用程序,然后执行热重载时,它会很好地获取数据,并且没有显示异常或警告。

List<Widget> elements = [];
if (snapshot.hasData) {
  for(int j = 0; j < snapshot?.data?.length; ++j) {
    elements.add(
      Container(child: Text(snapshot.data[j]["my_text"])
    )
  );
}

【问题讨论】:

    标签: flutter flutter-futurebuilder


    【解决方案1】:

    您的列表中需要一个对象,如下所示:

    Future<List<Album>> fetchAlbum() async { //Album is an object
      final response =
          await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
    
      if (response.statusCode == 200) {
        // If the server did return a 200 OK response,
        // then parse the JSON.
        return Album.fromJson(jsonDecode(response.body));
      } else {
        // If the server did not return a 200 OK response,
        // then throw an exception.
        throw Exception('Failed to load album');
      }
    }
    
    class Album {
      final int userId;
      final int id;
      final String title;
    
      Album({
        required this.userId,
        required this.id,
        required this.title,
      });
    
      factory Album.fromJson(Map<String, dynamic> json) {
        return Album(
          userId: json['userId'],
          id: json['id'],
          title: json['title'],
        );
      }
    }
    
    if (snapshot.hasData) {
      return Text(snapshot.data!.title); //title is String in Album
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2016-10-18
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多