英文:
Flutter: How can I add network check and showDialog on a Future function
问题
我在我的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 {
// 处理错误
}
} catch (error) {
// 处理错误
} finally {
// 关闭进度对话框
Navigator.of(context).pop();
}
}
@override
void initState() {
fetchData();
super.initState();
}
@override
Widget build(BuildContext context) {
return Container();
}
Future<http.Response> getProfileDetails() async {
if (await Utility.isInternet()) {
final SharedPreferences prefs = await SharedPreferences.getInstance();
// 从SharedPreferences读取值并调用API
final String url = "你的API路径";
final response = await http.get(Uri.parse(url));
return response;
} else {
// 显示无网络警告
throw Exception("没有网络连接");
}
}
}
关于你遇到的问题:
-
问题1: 进度对话框不显示在UI中。
- 我在
fetchData()
方法中添加了显示进度对话框的代码,并在try
块内部显示,同时在finally
块内关闭它,以确保它在API调用期间正确显示和关闭。
- 我在
-
问题2: 返回类型错误。
- 我在
getProfileDetails()
方法中添加了一个throw
语句,以处理没有网络连接的情况,并抛出一个异常。这样可以确保返回类型与函数签名匹配,解决了潜在的返回类型问题。
- 我在
英文:
I have below 2 methods in my Utility class: One for checking the network connection and on for showing the progress dialog.
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, ),
);
});
}
I need to apply it on the below API call section:
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
}
}
I added ProgressDialog
in the fetchData()
, like the commented code in the code, but it is not showing in the UI when calling the API.
Also I have added the network check on the getProfileDetails()
, but it is showing below error.
> The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<Response>', is a potentially non-nullable type. Try adding either a return or a throw statement at the end.
How can I fix these 2 issues?
答案1
得分: 3
每当你定义一个具有某种预期输出的方法时,你的代码应该返回与你定义的确切类型相同的类型,或者返回一个错误。
在你的代码中,你已经声明了一个类似这样的Future:
Future<http.Response> getProfileDetails() async{
你应该始终返回一个 Future<http.Response>
。
然而,当第一个 If 条件不为 True
时,没有要返回的内容,导致了错误。
英文:
Whenever you define a method that has some sort of expected output, your code should return the exact same type you defined or an error.
In your code you have declared a Future like this:
Future<http.Response> getProfileDetails() async{
You should always return a Future<http.Response>
.
However, when the first If condition is not True
, there is nothing to be returned, resulting in your error.
答案2
得分: 0
未固定的代码,添加了进度对话框和网络检查如下:
Future<http.Response?> getProfileDetails() async
{
if(await Utility.isInternet())
{
Utility.ShowProgress(context);
//从SharedPreferences读取值并调用API
final String url = 我的API路径;
final response = await http.get(Uri.parse(url));
Navigator.of(context).pop();
return response;
}
else
{
Utility.showToastMessage("无网络连接!",Toast.LENGTH_SHORT,
ToastGravity.CENTER, Colors.white, 16.0 );
return null;
}
}
英文:
The fixed code with progress dialog and network check adding below:
Future<http.Response?> getProfileDetails() async
{
if(await Utility.isInternet())
{
Utility.ShowProgress(context);
//reading values from SharedPreferences and calling the API
final String url = My API Path;
final response = await http.get(Uri.parse(url));
Navigator.of(context).pop();
return response;
}
else
{
Utility.showToastMessage("No internet connection!",Toast.LENGTH_SHORT,
ToastGravity.CENTER, Colors.white, 16.0 );
return null;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论