Flutter Class member list returns null even after initialization

Here is a folder model class:

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

The folders are getting created through API call like this:

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);
  }

And there's a list called "folders" which maps the folders fetched from the Library View API. The problem is that the folderContent list is empty on the creation of folder (which is fine and should be) but when these Folder object is get mapped to create a view, the folderContent returns null. Here is a code of a folderView:

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();
  }

When these folders get mapped as it shown above, the folderContent is null which shouldn't be according to the initialization done in the class model. I have tried initializing the folderContent to an empty list (see commented code in FolderView) but this doesn't suit my requirements as the list gets empty everytime the widget is rebuilded. The problem arises when I try to use map function which somehow sets folderContent to null. How do I resolve this?

EDIT: Debug Console Output When I try to create folder:

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

This shows that empty list is initialized which is what I want.

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

This is when folders get mapped to a list where 'folderContent' is null. 'test' is the title of folder.

1 answer

  • answered 2021-07-27 17:58 Tanay Neotia

    Can you try this?

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

    Usually to check the assignment of variables you don't need a function when the constructor is called, you can do it directly through the constructor. If you need to modify the list later with add or something, check if the list is empty and then if it is, instead of using add use =.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum