PopScope 中的泛型
概述
#为 PopScope
类添加了泛型类型,并将 onPopInvoked
替换为新方法 onPopInvokedWithResult
。新方法将布尔值 didPop
和 result
作为位置参数。
同样,出于相同的原因,将 Form.onPopInvoked
替换为 Form.onPopInvokedWithResult
。
背景
#以前,当调用 onPopInvoked
时,PopScope
没有办法访问 pop 结果。泛型类型被添加到 PopScope
类中,以便新方法 onPopInvokedWithResult
可以访问类型安全的(type-safe)结果。
变更说明
#向 PopScope
类添加了泛型类型 (<T>
) 和一个新方法 onPopInvokedWithResult
。onPopInvoked
属性已被弃用,取而代之的是 onPopInvokedWithResult
。
还向 Form
添加了一个新方法 onPopInvokedWithResult
来替换 onPopInvoked
。
迁移指南
#迁移前的代码
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
navigatorKey: nav,
home: Column(
children: [
Form(
canPop: false,
onPopInvoked: (bool didPop) {
if (didPop) {
return;
}
launchConfirmationDialog();
},
child: MyWidget(),
),
PopScope(
canPop: false,
onPopInvoked: (bool didPop) {
if (didPop) {
return;
}
launchConfirmationDialog();
},
child: MyWidget(),
),
],
),
),
);
}
迁移后的代码
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
navigatorKey: nav,
home: Column(
children: [
Form(
canPop: false,
onPopInvokedWithResult: (bool didPop, Object? result) {
if (didPop) {
return;
}
launchConfirmationDialog();
},
child: MyWidget(),
),
PopScope<Object?>(
canPop: false,
onPopInvokedWithResult: (bool didPop, Object? result) {
if (didPop) {
return;
}
launchConfirmationDialog();
},
child: MyWidget(),
),
],
),
),
);
}
泛型类型应与 PopScope
所在的 Route
的泛型类型匹配。例如,如果路由使用 int
作为其泛型类型,则应考虑使用 PopScope<int>
。
如果 PopScope
widget 在具有不同类型的多个路由之间共享,则可以使用 PopScope<Object?>
来捕获所有可能的类型。
时间线
#已合并到版本:3.22.0-26.0.pre
稳定版本:3.24.0
参考资料
#API 文档
相关议题
相关 PR
- 为 PopScope 中的结果添加泛型类型 (已回滚)
- 重新应用新的 PopScope API (最终重新合并)