Flutter拆分Scaffold到独立文件后出现Null check operator空值报错如何解决
问题根因
你的报错由两个代码问题共同导致:
- 拆分到独立文件的
myscaffoldfunc函数没有返回值,MaterialApp的home参数拿到的是null,触发了Flutter SDK内部的空校验异常 FloatingActionButton的onPressed属性直接执行了onpressedFun(),而不是传递函数引用,会导致初始化时就触发函数执行,不符合点击触发的预期
修复方案
直接修改Scaffold.dart代码即可,修改后代码如下:
import 'package:flutter/material.dart'; onpressedFun() => print("Hello"); // 补充返回值类型+return语句返回Scaffold组件 Widget myscaffoldfunc(){ return Scaffold( appBar: AppBar( title: Center(child: Text("Hello")), ), floatingActionButton: FloatingActionButton( // 去掉函数后的括号,传递函数本身而非执行结果 onPressed: onpressedFun, child: Icon(Icons.add), backgroundColor: Colors.amber, foregroundColor: Colors.white, hoverColor: Colors.amberAccent, ), body: Center(child: Text("Hello World")), ); }
修改后重新运行项目即可正常加载页面,无需改动main.dart代码。
内容的提问来源于stack exchange,提问作者Avijit
相关产品推荐
相关产品推荐

