Flutter升级2.5.2后webview_flutter报Not a constant expression错误如何解决?
报错原因
- Dart语法规定,被
const修饰的常量表达式内部所有属性值必须是编译期可确定的常量。匿名函数属于运行时创建的函数对象,不属于编译期常量,不能出现在const修饰的结构中。 - webview_flutter 2.1.0及以上版本将
WebView的构造函数调整为const构造,同时Flutter 2.5.2版本对常量表达式的校验规则更加严格。你在代码中给外层Center加了const修饰,编译器会递归校验Center的child(也就是WebView)的所有参数是否符合常量要求,而navigationDelegate传入的匿名函数不符合要求,因此触发报错。
解决方案
方案1(最简便,推荐)
直接去掉Center前的const修饰符即可,修改后代码如下:
body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: WebView( initialUrl: "https://xxxx", navigationDelegate: (navigation) { return NavigationDecision.navigate; }, ), ),
方案2(保留常量优化)
如果需要保留const修饰来获得组件常量缓存的性能收益,可以将navigationDelegate对应的处理逻辑提取为顶层函数或类的静态函数(这两类函数属于编译期常量),示例代码如下:
// 声明为顶层函数或者所在State/Widget的静态函数 NavigationDecision _handleNavigation(NavigationRequest navigation) { return NavigationDecision.navigate; } // 页面build方法中使用时保留const修饰 body: const Center( child: WebView( initialUrl: "https://xxxx", navigationDelegate: _handleNavigation, ), ),
内容的提问来源于stack exchange,提问作者boybeak
相关产品推荐
相关产品推荐

