1

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,
    )
  );
}

一切顺利吗?我看不出这里有什么区别......有人可以分享一些关于为什么会这样的见解吗?

4

1 回答 1

0

您收到错误是因为您在小部件const之前使用了关键字,AlignAlign小部件不是构造函数类型。

class NameContainer extends StatelessWidget {
 NameContainer({ required this.name, Key? key}) : super(key : key); // const remove from here 

final String name;

@override
Widget build(BuildContext context) {
  return Container(
    margin: const EdgeInsets.all(20.0),
    child:  Align( // here remove const
      alignment: Alignment.center,
      child: Text(
        name,
        textAlign: 
        TextAlign.center, 
        style: const TextStyle(
          fontWeight: FontWeight.bold,
        )
      )
    )
  );
}
于 2021-11-04T05:07:26.023 回答