error-handling - PlatformException 抛出意外
问题描述
ScopedModel
我从外部调用方法ScopedModel
(按下按钮)。但PlatformException
并没有像我预期的那样赶上。
PlatformException
仅在ScopedModel
Method中捕获try/catch
。它没有被按钮按下try/catch
。
按钮按下:
child: RaisedButton(
onPressed: () async {
try {
await loginModel.signInWithGoogle();
} on PlatformException catch (e) {
debugPrint(e.toString());
}
},
ScopedModel 方法:
await _signInWithGoogle();
…
Future<void> _signInWithGoogle() async {
…
throw PlatformException(code: ‘Test Exception’);
} on PlatformException catch (e) {
debugPrint(e.toString());
}
我投入PlatformException
以ScopedModel
测试何时从该方法引发异常。
为什么有区别?我想抓住PlatformException
按钮按下
感谢帮助!
解决方案
它应该工作。看一个非常简单的例子:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Login userLogin = Login();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Simple exception test',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
try {
await userLogin.signInWithGoogle();
} on PlatformException catch (e) {
print('Error ...:');
print(e);
}
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class Login {
Future<void> signInWithGoogle() async {
throw PlatformException(code: 'Test Exception');
}
}
推荐阅读
- amazon-web-services - 我是否需要静态 s3 网站的 aws 代码管道中的代码部署步骤
- java - 我该如何改进这个计算器(Bluej)?
- ruby-on-rails - Capistrano + puma + nginx:Capistrano puma 没有创建 puma-sockets 和 puma id
- python - NumPy 的 free-function-reshape() 与 member-function-reshape() 的实现?
- spring-boot - 如何从另一个模块导入安全配置类
- java - 正则表达式:匹配其他正则表达式留下的所有内容
- airflow - 气流:Bash Operator 没有给出结果
- python - 我需要什么语法来选择数据框中的单个行?
- excel - 防止记录重复记录的 VBA 脚本
- excel - 如何查找从今天起 14 天后的趋势/预测结果