-1

随着新的更新,一些 HTTP 功能发生了变化。这个功能以前可以用,现在不行了。有人可以解释发生了什么变化吗?

import 'package:http/http.dart';

    void getData() async {
    Response response = await get('https://jsonplaceholder.typicode.com/todos/1');
    Map data = JsonDecode(responce.body);
    print(data);
    }

lib/pages/loading.dart:24:37: Error: The argument type 'String' can't be assigned to the parameter type 'Uri'.
 - 'Uri' is from 'dart:core'.
      Response response = await get('https://jsonplaceholder.typicode.com/todos/1');
4

1 回答 1

0

你可以试试这个:

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

void getData() async {
  var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
  var data = jsonDecode(response.body) as Map;
  print(data);
}

更新:为WorldTimeApi 插入代码

网络服务:

class NetService {
  static Future<T?> getJson<T>(String url, {int okCode = 200}) {
    return http.get(Uri.parse(url))
      .then((response) {
        if (response.statusCode == okCode) {
          return jsonDecode(response.body) as T;
        }
        PrintService.showDataNotOK(response);
        return null;
      })
      .catchError((err) => PrintService.showError(err));
  }
}

主要的:

import 'dart:async';

import 'package:_samples2/networking.dart';

class WorldTimeApi {
  static const _url = 'http://worldtimeapi.org/api/timezone';

  static FutureOr<void> fetchTime(String relPath) async {
    await NetService.getJson(_url + relPath)
      .then((response) => print(response))
      .whenComplete(() => print('\nFetching done!'));
  }
}

void main(List<String> args) async {
  await WorldTimeApi.fetchTime('/America/Los_Angeles');
  print('Done!');
}

结果:

{abbreviation: PST, client_ip: 179.6.56.125, datetime: 2021-03-09T17:24:09.367903-08:00, day_of_week: 2, day_of_year: 68, dst: false, dst_from: null, dst_offset: 0, dst_until: null, raw_offset: -28800, timezone: America/Los_Angeles, unixtime: 1615339449, utc_datetime: 2021-03-10T01:24:09.367903+00:00, utc_offset: -08:00, week_number: 10}

Fetching done!
Done!
于 2021-03-09T23:50:10.760 回答