flutter null 安全参数类型“字符串?”不能分配给参数类型 'String'

时间:2021-05-18 15:24:22

标签: flutter dart dart-null-safety

我在我的 flutter 应用程序中使用了 null 安全性,我正在尝试将地图映射到漫游屏幕小部件。我在网上看过但没有看到解决方案。这是我的地图

final pageViewModel = [
{
  'title': 'Budget Your Funds And Save Up',
  'subtitle': 'Save Up Your Money Over A Period Of Time and Get',
  'image': 'assets/images/budget.svg'
},
{
  'title': 'Transfer Funds At Almost No Cost',
  'subtite': 'Our Transfer Rates Are At Absolutely No Cost.',
  'image': 'assets/images/finance.svg'
},
{
  'title': 'Get Free Virtual Cards',
  'subtitle': 'Your Days Of Going To The Bank Is Over'
}
];

然后在我的构建方法中,我使用这个地图列表来创建一个像这样的页面视图模型

IntroductionScreen(
  pages: pageViewModel
      .map((page) => PageViewModel(
            titleWidget: Text(
              page['title'], //Here is the line causing the error
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: secondaryColor,
                  fontWeight: FontWeight.w800,
                  fontSize: 25.0),
            ),
            body:
                "Here you can write the description of the page, to explain someting...",
            image: SvgPicture.asset(
              'assets/images/budget.svg',
              height: 400,
            ),
          ))
      .toList(),

我得到的错误是

The argument type 'String?' can't be assigned to the parameter type 'String'

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

当您创建 pageViewModel 数组时,您没有在那里使用任何类型,只是将一些对象放入数组中。因此,编译器不能说 page['title'] 不是 null - 它的类型是动态的。为了避免这种情况,您可以创建一个模型类:

class YourViewModel {
  final String title;
  final String subtitle;
  final String? image;

  const YourViewModel({
    required this.title,
    required this.title, 
    this.image,
  });
}

然后,您的 pageViewModel 将如下所示:

final pageViewModel = <YourViewModel>[
  YourViewModel(
    title: 'Budget Your Funds And Save Up',
    subtitle: 'Save Up Your Money Over A Period Of Time and Get',
    image: 'assets/images/budget.svg'
  ),
  YourViewModel(
    title: 'Transfer Funds At Almost No Cost',
    subtite: 'Our Transfer Rates Are At Absolutely No Cost.',
    image: 'assets/images/finance.svg'
  ),
  YourViewModel(
    title: 'Get Free Virtual Cards',
    subtitle: 'Your Days Of Going To The Bank Is Over'
  ),
];

全部完成,您应该不会在 UI 中看到错误!

奖励解决方案(不推荐,而且很麻烦,除非您知道自己在做什么):

如果您 100% 确定标题永远不会为空,您可以使用 bang 运算符:

page['title']!

这应该可行,但如果标题在任何时候为空,您将得到一个疯狂的运行时空指针异常。