首页 > 解决方案 > I/flutter(8876):捕获错误:错误状态:平台不允许不安全的 HTTP:

问题描述

我制作了一个使用世界时间 API 的颤振应用程序。它一直运行良好,直到有一天我从我的 github 配置文件下载它并尝试运行它。现在,它显示“错误:布尔表达式不能为空”。所以,我改变了它的值并初始化了它。然后它没有相应地改变它的价值。然后,当我在控制台上打印响应正文时,它显示 Bad state 错误:不允许 http 请求。

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

class WorldTime{

  String location; //location name for UI
  String time; // the time in that location
  String flag;//url to an asset flag icon
  String url; //location url for api endpoints
  bool isDayTime=true;

  WorldTime({ this.location,this.flag,this.url});

  Future<void> getTime() async {

    try{
      //make the request
      Response response = await 
      get('http://worldtimeapi.org/api/timezone/$url');
      print(response.body);
      Map data=jsonDecode(response.body);

      //get properties from data
      String datetime=data['datetime'];
      String offset = data['utc_offset'].substring(1,3);

      //create date time object
      DateTime now=DateTime.parse(datetime);
      now = now.add(Duration(hours: int.parse(offset)));

      //set time property
      isDayTime= now.hour>4 && now.hour<18?true:false;
      time=DateFormat.jm().format(now);
    }
    catch(e){
                       print('caught error: $e');
                       time='could not get time data';
    }


  }

}

我尝试过的事情:

  1. 更新了我的颤振和 Android 工作室。
  2. 创建了一个网络安全文件并尝试在 android manifest 文件中进行一些更改,然后它显示 Error parsing Android manifest file 所以后来,我撤消了更改。
  3. 确保我的模拟器已连接到互联网。

编辑:谢谢大家的帮助。这是一个愚蠢的小错误,我需要使用 https 而不是 http。它现在工作正常,谢谢大家。

标签: fluttergithubmobile-development

解决方案


您应该使用安全的 http (https://)。

改变这个:

Response response = await 
get('http://worldtimeapi.org/api/timezone/$url');

对此:

Response response = await 
get('https://worldtimeapi.org/api/timezone/$url');

推荐阅读