Flutter:如何在一个Future函数中添加网络检查和显示对话框

huangapple go评论135阅读模式
英文:

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. 问题1: 进度对话框不显示在UI中。

    • 我在fetchData()方法中添加了显示进度对话框的代码,并在try块内部显示,同时在finally块内关闭它,以确保它在API调用期间正确显示和关闭。
  2. 问题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&lt;bool&gt; 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&lt;UserDetails&gt; {
  ProfileResponse? profileResponse;
  Future&lt;void&gt; fetchData() async {
	try {
	  //Utility.ShowProgress(context);
	  final response = await getProfileDetails();
	  if (response.statusCode == 200) {
		Map&lt;String, dynamic&gt; parsedData = jsonDecode(response.body);
		setState(() {
		  profileResponse = ProfileResponse.fromJson(parsedData);
		});
	  } else {
		// setState(() {
		//   _data = &#39;Error: ${response.statusCode}&#39;;
		// });
	  }
	} catch (error) {
	  // setState(() {
	  //   _data = &#39;Error: $error&#39;;
	  // });
	}
	//Navigator.of(context).pop();
  }

  @override
  void initState() {
	fetchData();
  }
  
  @override
Widget build(BuildContext context) {
return Container(
     )
}
  
  Future&lt;http.Response&gt; 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&lt;http.Response&gt; getProfileDetails() async{

You should always return a Future&lt;http.Response&gt;.
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&lt;http.Response?&gt; 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(&quot;No internet connection!&quot;,Toast.LENGTH_SHORT,
		  ToastGravity.CENTER, Colors.white, 16.0 );
	  return null;
	}
}

huangapple
  • 本文由 发表于 2023年8月11日 01:29:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定