如何使用Flutter Semantics?如何解决const构造器调用报错问题?
报错根因
你使用的Flutter 2.5.0版本中,Semantics组件本身没有提供const构造方法,而你将Semantics放在了const Center的子组件位置,Dart要求const修饰的容器内所有子节点也必须是常量实例,因此触发The constructor being called isn't a const constructor报错。你单独给Text加const解决不了问题,因为报错的源头是Semantics本身不支持const构造。
解决办法
- 方案1:无需升级版本,直接去掉
Center前的const修饰即可,Text仍可保留const优化性能,修改后代码如下:
// Copyright 2018 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:english_words/english_words.dart'; import 'package:flutter/rendering.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: true, title: 'Welcome to Flutter', home: Scaffold( appBar: AppBar( title: const Text('Welcome to Flutter'), ), // 移除Center的const修饰 body: Center( child: Semantics(child: const Text('Hello World')), ), ), ); } }
该方案对常规应用的性能影响几乎可以忽略,是成本最低的修复方式。
- 方案2:如果希望保留常量优化,可以将Flutter稳定版升级到3.0及以上版本,更高版本的Flutter已经为
Semantics新增了const构造器,升级后直接按原有写法添加const修饰即可:
body: const Center( child: Semantics(child: Text('Hello World')), )
内容的提问来源于stack exchange,提问作者joels
相关产品推荐
相关产品推荐

