flutter 为什么这个AppBar小部件不工作?(后期初始化错误,空值上的空检查)

xggvc2p6  于 2023-05-23  发布在  Flutter
关注(0)|答案(2)|浏览(117)

我正在尝试重构一些重复的代码,使其更容易更新。第一个明显的候选者是我的项目重复使用scaffold appBar属性,该属性在二十多个位置是相同的(或几乎相同)。所以,我想把appBar变成一个小部件,在这里我可以只编写appBar: FbAppBar(title: 'Fonts'),,而不是在24个不同的文件中编写5或6行代码。
这是我的第一次尝试:

class FbAppBar extends StatelessWidget implements PreferredSizeWidget {
  FbAppBar({
    required String title,
    super.key,
  });

  late String title;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      systemOverlayStyle: SystemUiOverlayStyle.dark,
      foregroundColor: Colors.grey[800],
      backgroundColor: Colors.transparent,
      elevation: 0,
      title: Text(
        title.hardcoded,
        style: Theme.of(context).textTheme.titleLarge,
      ),
      actions: [],
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

这个^^在title变量上得到了一个“LateInitializationError”。所以,我把它修改成这样:

class FbAppBar extends StatelessWidget implements PreferredSizeWidget {
  FbAppBar({
    required String title,
    super.key,
  });

  String? title;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      systemOverlayStyle: SystemUiOverlayStyle.dark,
      foregroundColor: Colors.grey[800],
      backgroundColor: Colors.transparent,
      elevation: 0,
      title: Text(
        title!.hardcoded,
        style: Theme.of(context).textTheme.titleLarge,
      ),
      actions: [],
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

这让我得到了一个“Null check used on a null value”错误。
显然我错过了一些东西(希望简单)。标题不会为空(实际上),因为我从调用代码中传递了一个字符串(即appBar: FbAppBar(title: 'Fonts'),),但我不明白为什么这在这里不起作用。

s2j5cfk0

s2j5cfk01#

您缺少作业部分(即this)来分配title属性,所以它应该是这样的:

FbAppBar({
  required this.title,
  super.key,
});

final String title;
jw5wzhpr

jw5wzhpr2#

很可能在应用状态中有一个点title属性为null。此外,String没有getter hardcoded,除非你有一个***自定义扩展***为此创建。
您可以将您的FbAppBar更改为下面的。

class FbAppBar extends StatelessWidget implements PreferredSizeWidget {
  const FbAppBar({required this.title, super.key});

  final String? title;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      systemOverlayStyle: SystemUiOverlayStyle.dark,
      foregroundColor: Colors.grey[800],
      backgroundColor: Colors.transparent,
      elevation: 0,
      title: title != null
          ? Text(
              title!,
              style: Theme.of(context).textTheme.titleLarge,
            )
          : null,
      actions: [],
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}

相关问题