gpt4 book ai didi

error-handling - PlatformException引发意外

转载 作者:行者123 更新时间:2023-12-03 08:45:28 25 4
gpt4 key购买 nike

我从ScopedModel外部调用ScopedModel中的方法(按按钮时)。但是PlatformException未能如我所愿。
PlatformException仅在ScopedModel方法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');
}
}

关于error-handling - PlatformException引发意外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com