【问题标题】:Flutter - Can't pass class field into child componentFlutter - 无法将类字段传递给子组件
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 2021-07-04
  • 2018-09-23
相关资源
最近更新 更多