flutter null safety 参数类型'String?'不能赋值给参数类型'String'

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

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

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'
}
];

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

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'

任何帮助将不胜感激。

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

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']!

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