【问题标题】:Flutter Class member list returns null even after initializationFlutter 类成员列表即使在初始化后也返回 null
【发布时间】:2021-07-27 16:35:37
【问题描述】:

这是一个文件夹模型类:

import 'package:flutter/material.dart';

import 'block_model.dart';

class Folder {
  Folder({
    this.title = '',
  }) {
    this.folderContent = this.folderContent ?? <Block>[];
  }
  String title;
  List<Block> folderContent = [];
  String id;

  void renameFolder(String value) {
    title = value;
  }

  Folder.fromJson(Map<String, dynamic> json) {
    this.id = '${json['id']}';
    this.title = json['title'];
    this.folderContent = json['folderContent'];
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> folderJson = {};
    folderJson['id'] = this.id;
    folderJson['title'] = this.title;
    folderJson['folderContent'] = this.folderContent;
    return folderJson;
  }
}

这些文件夹是通过 API 调用创建的,如下所示:

Future<void> createLibraryFolder(String title) async {
    const String createFolderURL = '/api/TimelineLibrary/createFolder';
    Folder newFolder = Folder(title: title);
    var res =
        await request.postRequest(newFolder.toJson(), createFolderURL, false);
    print(res);
  }

还有一个名为“文件夹”的列表,它映射从 Library View API 获取的文件夹。问题是在创建文件夹时 folderContent 列表为空(这很好,应该是)但是当这些 Folder 对象被映射以创建视图时,folderContent 返回 null。这是一个文件夹视图的代码:

List<Widget> createFolders() {
    return _timeLineController.folders.map((Folder folder) {
      // if (folder.folderContent == null) {
      //   folder.folderContent = <Block>[];
      // }
      Widget folderWidget = Container(
        width: 300,
        margin: const EdgeInsets.all(3),
        child: FolderWidget(folder: folder),
      );
      return GestureDetector(
        onLongPressStart: (LongPressStartDetails details) {
          showMenu(
            color: kLightAccent,
            context: context,
            position: RelativeRect.fromLTRB(
                details.globalPosition.dx,
                details.globalPosition.dy,
                details.globalPosition.dx,
                details.globalPosition.dy),
            items: <PopupMenuEntry<String>>[
              PopupMenuItem(
                value: 'Menu',
                child: MenuItem(
                  'Edit',
                  () {
                    Navigator.pop(context);
                  },
                ),
              ),
            ],
          );
        },
        onPanUpdate: (DragUpdateDetails dragDetails) {
          if (dragDetails.delta.dx > 0) {
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text('Delete Folder?'),
                    content: Container(
                      height: 50,
                      width: 50,
                      alignment: Alignment.center,
                      child: Row(
                        children: <Widget>[
                          Spacer(),
                          ElevatedButton(
                              style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all<Color>(kOrange),
                                foregroundColor:
                                    MaterialStateProperty.all<Color>(
                                        Colors.white),
                              ),
                              onPressed: () async {
                                Navigator.pop(context);
                                await deleteLibraryFolder(folder.id);
                              },
                              child: Text('Yes')),
                          SizedBox(width: 10),
                          ElevatedButton(
                              style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all<Color>(kOrange),
                                foregroundColor:
                                    MaterialStateProperty.all<Color>(
                                        Colors.white),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: Text('No')),
                        ],
                      ),
                    ),
                  );
                });
          }
        },
        onTap: () {
          folderID = folder.id;
          setState(() {
            isCheck = true;
          });
        },
        child: folderWidget,
      );
    }).toList();
  }

当这些文件夹如上所示被映射时,folderContent 为空,这不应该根据类模型中完成的初始化。我尝试将 folderContent 初始化为一个空列表(请参阅 FolderView 中的注释代码),但这不符合我的要求,因为每次重建小部件时列表都会变空。当我尝试使用以某种方式将 folderContent 设置为 null 的 map 函数时,就会出现问题。我该如何解决这个问题?

编辑: 调试控制台输出 当我尝试创建文件夹时:

I/flutter (22459): []
I/flutter (22459): {id: 57}

这表明空列表已初始化,这是我想要的。

I/flutter (22459): 57
I/flutter (22459): test
I/flutter (22459): null

这是当文件夹被映射到“folderContent”为空的列表时。 'test' 是文件夹的标题。

【问题讨论】:

  • 您可以尝试将List&lt;Block&gt; folderContent = []; 替换为List&lt;Block&gt;? folderContent 或将this.folderContent = null ?? &lt;Block&gt;[]; 替换为this.folderContent.length&gt;0? this.folderContent: &lt;Block&gt;[];
  • 不行,两种方法都试过了,列表还是返回null。
  • 如果您没有得到任何空值,请尝试打印(调试)

标签: list flutter dart


【解决方案1】:

你可以试试这个吗?

 Folder({
    this.title = '',
    this.folderContent = const [],
  });

  String title;
  List<Block> folderContent;
  String id;

通常在调用构造函数时检查不需要函数的变量的赋值,可以直接通过构造函数进行。如果您稍后需要使用add 或其他内容修改列表,请检查列表是否为空,如果为空,则不要使用add,而是使用=

【讨论】:

  • 我尝试了上述方法,但是当我尝试将块添加到 folderContent 列表同时检查 folderContent 列表是否为空时,我得到了这个。 : getter 'isEmpty' 在 null 上被调用。接收者:null 尝试调用:isEmpty 即使我尝试检查它是否为空,它也可能在列表初始化为空时第一次起作用。但是每次都会以这种方式初始化列表,这也不是我想要的。
  • 在您的 OP 中,我看不到您在哪里调用 .isEmpty,您能否更新完整代码?谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
相关资源
最近更新 更多