You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter新手疑问:代码有误还是SSL证书/网络连接问题?

Flutter网络请求错误修复与排查

直接报错原因

你看到的type 'List<String>' is not a subtype of type 'String' in type cast错误,完全是代码写法问题,和网络、SSL没关系:
你写的String datetime = ['datetime'] as String;这段代码,是创建了一个包含'datetime'字符串的列表,然后强行把列表转成字符串,这必然触发类型转换错误。正确的做法是从你解析好的data字典里通过键名取值。

另外提个小细节:你把http包别名设成了https,虽然不影响运行,但不符合常规写法,建议改成http。

修正后的完整代码

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

class Loading extends StatefulWidget {
  const Loading({Key? key}) : super(key: key);
  @override
  State<Loading> createState() => _LoadingState();
}

class _LoadingState extends State<Loading> {

  void getTime () async {
    Uri url = Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London');
    http.Response response = await http.get(url);
    Map data = jsonDecode(response.body);

    // 正确从data字典中提取字段
    String datetime = data['datetime'] as String;
    String offset = data['offset'] as String;
    print(datetime);
    print(offset);
  }

  @override
  void initState() {
    super.initState();
    getTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('loading screen'),
    );
  }
}

关于网络/SSL问题的排查(你之前担心的点)

如果之后真遇到网络相关错误,可以这么查:

  • 先确认设备(模拟器/真机)能正常上网,用浏览器打开目标API地址,看能不能拿到返回的JSON数据
  • 如果是访问自签名证书的网站,Android需要在android/app/src/main/AndroidManifest.xml配置网络安全规则,iOS要在Info.plist里加例外;但你用的这个API是正规证书,大概率不会有SSL问题
  • 可以在请求代码外层加try-catch捕获异常,能更直观看到网络层面的错误信息

内容的提问来源于stack exchange,提问作者aclmonkebren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 06:52:39