如何解决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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。