Flutter - Dispose a variable

101

You're not using selectedImagesList defined in the state, instead, you're using selectedImagesList defined in PostNotifier class. so inside dispose method you should clear selectedImagesList defined in PostNotifier class.

Share:
101
rawm
Author by

rawm

I'm learning and trying to make stuff that could help make the world better. Freedom and democracy are the current goals.

Updated on January 03, 2023

Comments

  • rawm
    rawm over 1 year

    I have a page to create posts. I'm using image_picker package to get images and there's a provider that gets the images to the post creation page. There's a variable selectedImagesList that stores the list of picked images to be shown after they're picked by user.

    class _AddPostViewState extends State<AddPostView> {
      TextEditingController postTextController = TextEditingController();
      PostNotifier postNotifier(bool renderUi) =>
          Provider.of<PostNotifier>(context, listen: renderUi);
      int activeImageIndex = 0;
      List<File>? selectedImagesList = [];
    
      @override
      void initState() {
        postTextController = TextEditingController();
        super.initState();
      }
    
      @override
      void dispose() {
        print("disposing stuff");
        selectedImagesList = [];
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        selectedImagesList = postNotifier(true).selectedPostImages;
    
        return GestureDetector(
          onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
          child: Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.white,
              title: const Text(
                "New Post",
                style: TextStyle(color: Colors.black),
              ),
              centerTitle: true,
            ),
            body: SingleChildScrollView(
              child: Column(children: [
                Column(
                    Container(
                      child: TextField(
                        controller: postTextController,
                        decoration: const InputDecoration(
                            hintText: "Write something here..."),
                      ),
                    ),
                    const SizedBox(
                      height: 5,
                    ),
                    ElevatedButton(
                        onPressed: () {
                          postNotifier(false).pickPostImages();
                        },
                        child: selectedImagesList == null
                            ? const Text("Add Images")
                            : const Text("Reselect Images")),
    
                    if (postNotifier(true).selectedPostImages != null) ...[
                      Container(
                        padding: const EdgeInsets.all(25.0),
                        height: 420,
                        width: 396,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            CarouselSlider.builder(
                                options: CarouselOptions(
                                  onPageChanged: (index, reason) =>
                                      setState(() => activeImageIndex = index),
                                ),
                                itemCount: selectedImagesList!.length,
                                itemBuilder:
                                    (BuildContext context, index, realIndex) {
                                  final selectedImage = selectedImagesList?[index];
                                  return buildImage(selectedImage!, index);
                                }),
                            const SizedBox(
                              height: 21,
                            ),
                            buildDotIndicator(),
                          ],
                        ),
                      ),
                    ] else ...[
                      const SizedBox(
                        height: 0,
                      ),
                    ],
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                        onPressed: () async {
                          final authenticationNotifier =
                              Provider.of<AuthenticationNotifier>(context,
                                  listen: false);
                          var userEmail = await authenticationNotifier
                              .fetchUserEmail(context: context);
                          var postText = postTextController.text;
                          await postNotifier(false)
                              .uploadPostImageList(context: context);
                          var postMedia = postNotifier(false).uploadedImageUrlList;
    
                          if (postMedia != null) {
                            await postNotifier(false)
                                .addMultiImagePost(
                                    context: context,
                                      //post dto
                                    )
                                .whenComplete(
                              () {
                                SnackBarUtility.showSnackBar(
                                    message: "Post added to database",
                                    context: context);
                                postTextController.clear();
                                selectedImagesList = [];
                                Navigator.of(context).popAndPushNamed(HomeRoute);
                              },
                            );
                          } else {
                            SnackBarUtility.showSnackBar(
                                message: "Something went wrong", context: context);
                          }
                        },
                        child: const Text("Post")),
                  ],
                )
              ]),
            ),
          ),
        );
    

    I'm able to clear the postTextController by using .whenComplete() but the selectedImagesList still remains there and subsequent posts have images from previous posts.

    As evident in above code I've tried to set selectedImagesList to empty at the void dispose() function as well but it's not working. How to dispose the images once post is uploaded

  • rawm
    rawm about 2 years
    could you please help me with the code. I put the line postNotifier(false).selectedPostImages = []; in dispose() but I'm getting an error: There isn’t a setter named 'selectedPostImages' in class 'PostNotifier'.
  • AmirHossein Mohammadzadeh
    AmirHossein Mohammadzadeh about 2 years
    do it like this: postNotifier(false).selectedPostImages.clear()