我的Utility类中有以下两个方法:一个用于判断网络连接,另一个用于显示进度对话框.
static Future<bool> isInternet() async
{
bool result = await InternetConnectionChecker().hasConnection;
return result;
}
static ShowProgress(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Center(
child: SpinKitRotatingCircle(color: const Color(0xff2799fa), size: 60.0, ),
);
});
}
我需要将其应用于以下API调用部分:
class _UserDetailsState extends State<UserDetails> {
ProfileResponse? profileResponse;
Future<void> fetchData() async {
try {
//Utility.ShowProgress(context);
final response = await getProfileDetails();
if (response.statusCode == 200) {
Map<String, dynamic> parsedData = jsonDecode(response.body);
setState(() {
profileResponse = ProfileResponse.fromJson(parsedData);
});
} else {
// setState(() {
// _data = 'Error: ${response.statusCode}';
// });
}
} catch (error) {
// setState(() {
// _data = 'Error: $error';
// });
}
//Navigator.of(context).pop();
}
@override
void initState() {
fetchData();
}
@override
Widget build(BuildContext context) {
return Container(
)
}
Future<http.Response> getProfileDetails() async{
if(await Utility.isInternet()){
final SharedPreferences prefs = await SharedPreferences.getInstance();
//reading values from SharedPreferences and calling the API
final String url = My API Path;
final response = await http.get(Uri.parse(url));
return response;
}
else{
//show no network alert
}
}
我在fetchData()
中添加了ProgressDialog
,就像代码中的注释代码一样,但在调用API时,它不会显示在UI中.
另外,我已经在getProfileDetails()
上添加了网络判断,但它显示以下错误.
正文可能正常完成,从而导致返回""Null"",但返回类型""FutureOr""可能是不可为Null的类型.""try 在结尾处添加一个Return或Throw语句.
我如何解决这两个问题?