网络服务:
class NetService {
static Future<T> getJson<T>(String url) {
return http.get(Uri.parse(url))
.then((response) {
if (response.statusCode == 200) {
return jsonDecode(response.body) as T;
}
print('Status Code : ${response.statusCode}...');
return null;
})
.catchError((err) => print(err));
}
}
主要:
import 'package:_samples2/networking.dart';
class Country {
static const url = 'https://restcountries.eu/rest/v2/name/colombia';
static Future<List> getColombiaInfo() async {
print('Start fetching...');
return await NetService.getJson<List>(url).whenComplete(() => print('Fetching done!'));
}
}
void main(List<String> args) async {
var info = await Country.getColombiaInfo();
print(info);
}
结果:
Start fetching...
Fetching done!
[{name: Colombia, topLevelDomain: [.co], alpha2Code: CO, alpha3Code: COL, callingCodes: [57], capital: Bogotá, altSpellings: [CO, Republic of Colombia, República de Colombia], region: Americas, subregion: South America, population: 48759958, latlng: [4.0, -72.0], demonym: Colombian, area: 1141748.0, gini: 55.9, timezones: [UTC-05:00], borders: [BRA, ECU, PAN, PER, VEN], nativeName: Colombia, numericCode: 170, currencies: [{code: COP, name: Colombian peso, symbol: $}], languages: [{iso639_1: es, iso639_2: spa, name: Spanish, nativeName: Español}], translations: {de: Kolumbien, es: Colombia, fr: Colombie, ja: コロンビア, it: Colombia, br: Colômbia, pt: Colômbia, nl: Colombia, hr: Kolumbija, fa: کلمبیا}, flag: https://restcountries.eu/data/col.svg, regionalBlocs: [{acronym: PA, name: Pacific Alliance, otherAcronyms: [], otherNames: [Alianza del Pacífico]}, {acronym: USAN, name: Union of South American Nations, otherAcronyms: [UNASUR, UNASUL, UZAN], otherNames: [Unión de Naciones Suramericanas, União de Nações Sul-Americanas, Unie van Zuid-Amerikaanse Naties, South American Union]}], cioc: COL}]