Flutter / Dart-引发异常时重定向到屏幕的按钮吗?

问题描述

当前,当引发异常时,用户将面临一张空白的空白页面,该页面仅注明,

“我们无法成功下载json数据”

但是我想通过提供一个重定向到主页的按钮来提供一个安全网。关于如何做到这一点的任何想法?这是引发异常的代码

Future<List<ReplyContent>> downloadJSON({String replyid}) async {

  final jsonContent = "http://example.com/getpost.PHP";

  final response = await get(jsonContent);

  if (response.statusCode == 200) {
    List replycrafts = json.decode(response.body);
    return replycrafts
        .map((replycraft) => new ReplyContent.fromJson(replycraft))
        .toList();
  } else
    throw Exception('We were not able to successfully download the json data.');
}

解决方法

调用Future时,可以使用catchError方法。

downloadJSON().catchError((e)=> print(e)); // Example

然后在小部件中,您可以使用布尔值来显示或不显示按钮。

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool shouldShowButton = false;
  
  Future downloadJSON()async{
    throw("ERROR!");
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,home: Scaffold(
        appBar: AppBar(),body: Container(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,mainAxisAlignment: MainAxisAlignment.center,children: [
                   FlatButton(
                  child: Text("Call Future"),onPressed: (){
                    downloadJSON().catchError((e)=>setState(()=> shouldShowButton = true));
                  },),shouldShowButton? FlatButton(
                  child: Text("Go back"),onPressed: ()=> Navigator.of(context).pop(),): Container(),],)
          ),);
  }
}

这样,在调用Future时,您可以简单地使用setState将ShouldShowButton的值更新为true。