我现在正在通过观看Udemy上的视频课程来学习Flutter 翼.

随着演讲者的一步一步走,我最终犯了一个我无法摆脱的错误.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter JSON demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Future<OfficesList> officesList;

  @override
  void initState() {
    super.initState();
    officesList = getOfficesList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Manual JSON serialization'),
        centerTitle: true,
      ),
      body: FutureBuilder<OfficesList>(
        future: officesList,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data?.offices.length,
              itemBuilder: (context, index) {
                return Card(
                  child: ListTile(
                    title: Text('${snapshot.data?.offices[index].name}'),
                    subtitle: Text('${snapshot.data?.offices[index].adress}'),
                    leading:
                        Image.network('${snapshot.data?.offices[index].image}'),
                    isThreeLine: true,
                  ),
                );
              },
            );
          } else if (snapshot.hasError) {
            return Text(snapshot.error.toString());
          } else {
            return const Text('null');
          }
          // return const Center(
          //   child: CircularProgressIndicator(),
          // );
        },
      ),
    );
  }
}

    import 'dart:convert';
import 'package:http/http.dart' as http;

class OfficesList {
  List<Office> offices;
  OfficesList({required this.offices});

  factory OfficesList.fromJson(Map<String, dynamic> json) { 
    var officesJson = json['offices'] as List;    // <-- the problem might be somewhere here 
    List<Office> officesList =
        officesJson.map((i) => Office.fromJson(i)).toList as List<Office>;

    return OfficesList(
      offices: officesList,
    );
  }
}

class Office {
  String? name;
  String? adress;
  String? image;

  Office({
    required this.name,
    required this.adress,
    required this.image,
  });

  factory Office.fromJson(Map<String, dynamic> json) {
    return Office(
        name: json['name'] as String,
        adress: json['adress'] as String,
        image: json['image'] as String);
  }
}

Future<OfficesList> getOfficesList() async {
  const url = 'https://about.google/static/data/locations.json';
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    return OfficesList.fromJson(json.decode(response.body));
  } else {
    throw Exception('Error: ${response.reasonPhrase}');
  }
}


Here's error i get

他编写代码的方式可能是问题所在,因为视频有点老了(大约.1-2年).

我在谷歌上搜索了这个问题,试图在列表中添加一些论点,等等,但都没有帮助.

如果有任何建议,我将不胜感激.

推荐答案

The problem was String named adress in Office constructor. Key from JSON is named address.
So it was returning null, because there's no key named adress

class Office {
  String? name;
  String? adress;
  String? image;

  Office({
    required this.name,
    required this.adress, // <-- "adress" instead of "address
    required this.image,
  });

  factory Office.fromJson(Map<String, dynamic> json) {
    return Office(
        name: json['name'] as String,
        adress: json['adress'] as String, // <-- "adress" instead of "address
        image: json['image'] as String);
  }
}

Flutter相关问答推荐

错误:找不到字体功能类型.Ffltter Google_Fonts包错误

Flutter版本3.19.2需要更新版本的Kotlin Gradle插件./android/build.gradle:ext.kotlin_version = latest-version>'

本机调试符号包含无效的目录调试符号.目前仅支持Android ABI

使用GO_ROUTER在模式内导航

如何使用Dio/Ffltter(前端)和amp;Go(后端)向API发送正确的请求

将侧边菜单和底部导航栏放在同一Flutter 应用程序中

我怎样才能go 掉这个底部导航栏上的白色背景

如何在Flutter 中使用滚动展开窗口小部件

如何翻转这种剪刀设计

Select 文本时如何更改 Flutter 中的光标 colored颜色 ?

Flutter 未处理的异常 - 对 null 值使用 Null 判断运算符

运行任何 flutter 命令都会显示无法安装 <版本>

具有 BLOC 和存储库模式的 Flutter Workmanager

如何格式化网址?

如何在图像上点或(图像的一部分)在 flutter 中点击?

扩展磁贴尾随图标在与一个磁贴交互时更新列表中的所有内容.如何只更改展开图块的图标?

在 Android 12+ 中,REST API 调用在 flutter 中非常慢,在 WiFi 中需要 10 秒,而在移动数据中不到一秒

我几乎每次都将 Stateless Widget 与 BLoC 一起使用.我错了吗?

如何使用 Riverpod 在运行时动态创建提供程序?

设计响应式卡片的最佳方法,以避免像素溢出错误或 _AssertionError