pubspec.yaml
,安裝 https://pub.dev/packages/dio,並執行 pub get
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dio: ^3.0.10
import 'package:dio/dio.dart';
Future<Response> getCountriesData() async {
Response res;
try {
res = await Dio().get("https://corona.lmao.ninja/v3/covid-19/countries");
if (res.statusCode == 200 && res.data != null) {
return res;
}
} on DioError catch (e) {
print('Dio error: ${e}');
} catch (e) {
print('Other error: ${e}');
}
return res;
// //若Widget已經掛載
// if (mounted) {
// //改變狀態
// setState(() {});
// }
}
Map allData = {};
Future<Response> getData() async {
try {
Response res = await Dio().get("https://corona.lmao.ninja/v2/all");
if (res.statusCode == 200 && res.data != null) {
allData = res.data;
// print(res);
}
} on DioError catch (e) {
print('Dio error: ${e}');
} catch (e) {
print('Other error: ${e}');
}
//若Widget已經掛載
if (mounted) {
//改變狀態
setState(() {});
}
}
//State狀態初始化
@override
void initState() {
// 要先做父類的State狀態初始化
super.initState();
//再做自己的事,如取得資料
getData();
}