【发布时间】:2021-12-18 09:56:38
【问题描述】:
刚接触 Flutter,我想开始让我的应用更加动态。我想首先将数据传递给我的 Text() 小部件,但我收到了这个奇怪的 null 错误,不知道为什么会这样。
目前我正在这样做,我传入name并在容器中的Text小部件中查看它:
class NameContainer extends StatelessWidget {
const NameContainer({ required this.name, Key? key}) : super(key : key);
final String name;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(20.0),
child: const Align(
alignment: Alignment.center,
child: Text(
name,
textAlign:
TextAlign.center,
style: const TextStyle(
fontWeight: FontWeight.bold,
)
);
)
);
}
但是它给了我一个A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword 错误。
但是,当我删除容器并只返回这样的文本时:
class NameContainer extends StatelessWidget {
const NameContainer({ required this.name, Key? key}) : super(key : key);
final String name;
@override
Widget build(BuildContext context) {
return Text(
name,
textAlign:
TextAlign.center,
style: const TextStyle(
fontWeight: FontWeight.bold,
)
);
}
一切顺利吗?我看不出这里有什么区别...谁能分享一些关于为什么会这样的见解?
【问题讨论】:
-
我认为你应该将变量声明放在构造函数之前。将“最终字符串名称”放在“const NameContainer({...})”之前。
-
@Kanon48 没关系,但约定是在构造函数之前声明变量。
标签: flutter flutter-text