Julien
Julien

Reputation: 1

Handling a Dynamic ListView.builder in Flutter

I manage a ListView.builder inside a Drawer that should show all my friend requests. By clicking on any item in these friend requests, I can access another page (OtherProfilePage) where I see the details of the friend request and can accept/decline the friend request.

However, when I accept/decline my friend request, I encounter the two following errors:

Null check operator used on a null value

The relevant error-causing widget was: 
  OtherProfilePage OtherProfilePage:file:///C:/Users/Julien/StudioProjects/opinions/lib/main.dart:117:58
When the exception was thrown, this was the stack: 
#0      _OtherProfilePageState.build (package:opinions/pages/other_profile_page.dart:356:40)
#1      StatefulElement.build (package:flutter/src/widgets/framework.dart:5729:27)
#2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5617:15)
#3      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5780:11)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:5333:7)
#5      BuildScope._tryRebuild (package:flutter/src/widgets/framework.dart:2693:15)
#6      BuildScope._flushDirtyElements (package:flutter/src/widgets/framework.dart:2752:11)
#7      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:3048:18)
#8      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:1162:21)
#9      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:468:5)
#10     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1397:15)
#11     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1318:9)
#12     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1176:5)
#13     _invoke (dart:ui/hooks.dart:312:13)
#14     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:419:5)
#15     _drawFrame (dart:ui/hooks.dart:283:31)
====================================================================================================

RangeError (length): Invalid value: Valid value range is empty: 0

The relevant error-causing widget was: 
  OtherProfilePage OtherProfilePage:file:///C:/Users/Julien/StudioProjects/opinions/lib/main.dart:117:58
When the exception was thrown, this was the stack: 
#0      List.[] (dart:core-patch/growable_array.dart)
#1      findFindRequestMap (package:opinions/utils/functions/friends_functions.dart:30:39)
#2      _OtherProfilePageState.build (package:opinions/pages/other_profile_page.dart:45:17)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:5729:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5617:15)
#5      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5780:11)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:5333:7)
#7      BuildScope._tryRebuild (package:flutter/src/widgets/framework.dart:2693:15)
#8      BuildScope._flushDirtyElements (package:flutter/src/widgets/framework.dart:2752:11)
#9      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:3048:18)
#10     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:1162:21)
#11     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:468:5)
#12     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1397:15)
#13     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1318:9)
#14     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1176:5)
#15     _invoke (dart:ui/hooks.dart:312:13)
#16     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:419:5)
#17     _drawFrame (dart:ui/hooks.dart:283:31)
====================================================================================================

Here is my code :

Drawer :

return Drawer(
      child: ListView(
        children: [
          DrawerHeader(
            child: Text(
              (length <= 1) ? "Find Request" : "Find Requests",
              style: Theme.of(context).textTheme.headlineSmall,
            ),
          ),
          if (length == 0)
            ListTile(
              title: Text("No find request"),
            )
          else
            ListView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: length,
              itemBuilder: (context, index) {
                if (index >= length) {
                  return SizedBox.shrink();
                }
                final request = userProvider.userAccount!.findsRequest[index];
                final findAccount = userProvider.findsRequest[index];

                return InkWell(
                  child: ListTile(
                    leading: AvatarLogo(
                      onPressed: () {
                        appProvider.setAccountVisited(findAccount);
                        context.goNamed(
                          OtherProfilePage.routeName
                        );
                      },
                      width: 40,
                      height: 40,
                      backgroundImage: (request["photo"] == null ||
                          request["photo"] == "")
                          ? null
                          : AssetImage(request["photo"]!),
                      childIcon: (request["photo"] == null ||
                          request["photo"] == "")
                          ? Icon(Icons.person, size: 30, color: Colors.black)
                          : null,
                    ),
                    title: Text(request["pseudo"]!),
                    subtitle: Text(
                      request["message"]!,
                      overflow: TextOverflow.ellipsis,
                    ),
                    trailing: Icon(Icons.arrow_forward_ios),
                    onTap: () {
                      print(findAccount);
                      appProvider.setAccountVisited(findAccount);
                      context.goNamed(
                        OtherProfilePage.routeName);
                    },
                  ),
                );
              },
            ),
        ],
      ),
    );

Elevated Button Accept of my OtherProfilePage

ElevatedButton(
                      onPressed: () {
                          //... Other cases
                        if (findRequested) {
                          setState(() {
                            isLoading = true;
                          });
                          print("Add new find");
                          userProvider.addNewFind(otherUserAccountPage.uid,
                              userProvider.userAccount!);
                          print("Added find");
                          userProvider.addNewFind(userProvider.userAccount!.uid,
                              otherUserAccountPage);
                          print("Added find");
                          userProvider.deleteFindRequest(otherUserAccountPage);
                          setState(() {
                            find = true;
                            findRequested = false;
                            isLoading = false;
                            print("userAccount: ${otherUserAccountPage}");
                          });
                        } 

And my deleteFindRequest function:

void deleteFindRequest(UserAccount user) {
    print("deleteFindRequest");
    userAccount!.findsRequest.removeWhere((element) => element['uid'] == user.uid);
    user.findsRequested.removeWhere((element) => element == userAccount!.uid);
    DbHelper.updateUser(user);
    updateActualUser();
    print("done");
    notifyListeners();
  }

Initially, I thought this error was due to passing my userAccount as an extra to OtherProfilePage, and when the list becomes empty, the extra also becomes empty, causing my other page to crash. However, after modifying my approach to use a provider for extra, the error persists. I suspect this is due to the ListView.builder not being able to handle the change in length, but I'm not sure...

Upvotes: 0

Views: 33

Answers (0)

Related Questions