PlatformException抛出意外

问题描述 投票:0回答:1

我从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

感谢帮助!

error-handling dart flutter scoped-model
1个回答
0
投票

它应该工作。看一个非常简单的例子:

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');
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.