【问题标题】:How to fix the getter length was called on null in Flutter如何修复 getter 长度在 Flutter 中被调用为 null
【发布时间】:2021-06-25 21:42:19
【问题描述】:

我收到 NoSuchMethodError: The gettter 'length' was called on null 所以我想知道如何解决这个问题。

当我尝试获取收藏值的长度时发生了问题。

最喜欢的视图模型

class FavoriteViewModel extends BaseViewModel {
  List<FavoriteModel> favorites = [];   

  void initialize(FavoriteService favProvider) {
    favorites = favProvider.getFavorites();
  }
}

重新排序屏幕

class _ReorderPageState extends State<ReorderPage> {
  @override
  Widget build(BuildContext context) {
    var favProvider = Provider.of<FavoriteService>(context, listen: true);
    return BaseView<FavoriteViewModel>(onModelReady: (model) {
      model.initialize(favProvider);
    }, builder: (context, model, child) {
      return model.state == ViewState.Busy
......


  Widget reorderWidget(FavoriteViewModel model, BuildContext bcontext) {
    return Theme(
      data: ThemeData(primaryColor: Colors.transparent),
      child: ReorderableListView(
        onReorder: (int oldIndex, int newIndex) {
          _onParentReorder(oldIndex, newIndex, model);
        },
        scrollDirection: Axis.vertical,
        children: List.generate(
          model.favorites.length,    // I think the issue is in this line
          (index) {
            FavoriteModel favorite = model.favorites[index]; // I think the issue is in this line

【问题讨论】:

  • 这几乎总是表明未正确管理 Future。这件事的许多答案已经在这里得到了回答。请搜索“flutter call on null”。

标签: flutter dart flutter-layout flutter-dependencies flutter-web


【解决方案1】:

您是否已经尝试过使用 elvis 运算符(类似于 typescript 和 kotlin)?


model?.favorites?.length

而且,它可能在您的 viewModel 初始化程序中 favProvider.getFavorites() 始终为 null ??

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 2020-03-20
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多