无法在 flutter RouteGenerator 类VerifyFirebaseOtpScreen戈德鲍尔说

如何解决无法在 flutter RouteGenerator 类VerifyFirebaseOtpScreen戈德鲍尔说

我想做什么?

像往常一样,我试图将数据从一个屏幕发送到另一个 onGenerateRoute(),但我的屏幕不接受参数类型并显示错误 参数类型“对象?”无法分配给参数类型“Map”。

我还尝试在接收器屏幕上更改参数类型 Object?,但现在我无法将数据从 Object 提取到 Map<String,dynamic>。我认为两者都是相同的数据类型,但空安全版本的处理方式不同。我认为这是一个错误。

我已经看到 flutter official documentation for navigate-with-arguments 并且当我在 Interactive example 部分切换到 null-safety 时,它也显示错误。查看此屏幕截图或自己尝试。

Screenshot 2021-03-30 at 20 13 56

它在非空安全版本的 flutter 中正常工作

这是片段

RouteGenerator 类

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    // Getting arguments passed while calling Navigator.pushNamed
    final args = settings.arguments;
    switch (settings.name) {
      case HomeScreen.routeName:
        return MaterialPageRoute(
          builder: (context) => HomeScreen(),);
      case LoginScreen.routeName:
        return MaterialPageRoute(
          builder: (context) => LoginScreen(),);
      case VerifyFirebaseOtpScreen.routeName:
        return MaterialPageRoute(
          builder: (context) => VerifyFirebaseOtpScreen(data: args),// Here is the error: The argument type 'Object?' can't be assigned to the parameter type 'Map<String,dynamic>'.
        );
      case AboutScreen.routeName:
        return MaterialPageRoute(
          builder: (context) => AboutScreen(),);
      default:
        return MaterialPageRoute(
          builder: (context) => Scaffold(
            body: SafeArea(
              child: Center(
                child: Text('No route defined for ${settings.name}'),),);
    }
  }
}

VerifyFirebaseOtpScreen

class VerifyFirebaseOtpScreen extends StatelessWidget {
  static const String routeName = '/verify_firebase_otp_screen';

  final Map<String,dynamic> data;

  const VerifyFirebaseOtpScreen({
    Key? key,required this.data,}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },child: Scaffold(
        body: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(8.0),child: Container(
              width: double.infinity,child: VerifyFirebaseOtpScreenDataSection(
                mobile: '${data['mobile']}',);
  }
}

日志
abhishekkumar@Abhisheks-MacBook-Air ~ % flutter doctor -v
[✓] Flutter (Channel beta,2.1.0-12.2.pre,on macOS 11.2.3 20D91 darwin-x64,locale en-IN)
    • Flutter version 2.1.0-12.2.pre at /Users/abhishekkumar/flutter
    • Framework revision 5bedb7b1d5 (13 days ago),2021-03-17 17:06:30 -0700
    • Engine revision 711ab3fda0
    • Dart version 2.13.0 (build 2.13.0-116.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/abhishekkumar/Library/Android/sdk
    • Platform android-30,build-tools 30.0.2
    • ANDROID_HOME = /Users/abhishekkumar/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.4,Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      ? https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      ? https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.17.0

[✓] Connected device (3 available)
    • iPhone SE (1st generation) (mobile) • 035FA189-09FF-46B5-96AC-C34E8D068C21 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
    • macOS (desktop)                     • macos                                • darwin-x64     • macOS 11.2.3 20D91 darwin-x64
    • Chrome (web)                        • chrome                               • web-javascript • Google Chrome 89.0.4389.90

• No issues found!

解决方法

简单回答

使用类型转换运算符 as 所以上述问题的答案将类似于 final args = settings.arguments as Map<String,dynamic>;

回答说明

我也将此问题提交为 an issue on GitHub 并感谢 goderbauer(Flutter 团队成员)正确识别此问题并通过提供 an appropriate solution 关闭它。

戈德鲍尔说

在您的示例中,settings.arguments 的类型为 Object?,您将其传递给 VerifyFirebaseOtpScreen.data,后者的类型为 Map<String,dynamic>。在空安全之前,这是合法的,被称为隐式向下转型。但是有了空安全,Dart 已经完全删除了隐式向下转换(您可以在此处阅读更多相关信息 https://dart.dev/null-safety/understanding-null-safety,只需在页面上搜索“隐式向下转换”即可)。所以现在,如果您确定 settings.argumentsMap<String,dynamic> 类型的行为,您需要进行显式转换,例如:settings.arguments as Map<String,dynamic>

他还说

(一旦我们将它们迁移到空安全,页面上的示例也必须更新)

dart.dev 解释和示例

参考文档页面 Understanding null-safety & using-nullable-types 解释也涵盖了这一点。

他们下面的例子已经足够解释了

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-