你可以试试这个:
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!