首页 > 解决方案 > 如何在颤振中创建套接字异常屏幕?

问题描述

在我的颤振项目中,当调用 API 时发生套接字异常时,我需要显示一些插图图像。我怎样才能做到这一点 ?

提前致谢

标签: flutterapidartexceptionsocketexception

解决方案


这取决于您要在小部件树中显示的位置。一个简单的示例是将新屏幕推送到导航堆栈。您将需要在可能发生异常的函数中使用 BuildContext。

void someMethod(BuildContext context) {
    try {
      //some code that might throw an exception
    } on Exception catch (_) {
      Navigator.pushNamed(context, "Your illustration view");
    }
  }

另一个示例是根据布尔值将其添加到您的小部件树中。当抛出异常时,您将该 bool 设置为 true。

void someOtherMethod() {
    try {
      //some code that might throw an exception
    } on Exception catch (_) {
      setState(() {
      hasThrownError = true; 
      });
    }
  }

在您的小部件树中使用它,如下所示:

bool hasThrownError = false;

  Widget buildWidgetTree() {
    return hasThrownError
        ? Text("This is where you can show your error illustration")
        : Text("This is wher you can show your regular view");
  }

推荐阅读