2

I use this code to upload picture to firebase Firestore. The uploading code is fine. But what if the user cancels the upload in the middle of the uploading process. Because Android user actually have the Back Button, right. Once they click it, the uploading process should be canceled. Once they do that, I received some kind of error message. How do I solve it?

Future<bool> uploadToFirebase(
        File image,
        String path,
        String tag,
        String number,
      ) async {
        // get userID
        final FirebaseAuth _auth = FirebaseAuth.instance;
        FirebaseUser user = await _auth.currentUser();
        String userID = user.uid;
    
        // get timeStamp
        var datetime = DateTime.now();
        var timeStamp = '${datetime.millisecondsSinceEpoch}';
    
        // set tag; currently undefined
        // tag = tag != null ? tag : 'notag';
    
        print('ID: ${user.uid}');
    
        final StorageReference firebaseStorageRef = FirebaseStorage.instance
            .ref()
            .child('$path/${userID}_${timeStamp}_${number}_${tag}.jpg');
    
        final StorageUploadTask uploadTask = firebaseStorageRef.putFile(image);
        print('uploadTask : $uploadTask');
    
        final StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
        print('uploadTask : ${uploadTask.isSuccessful}');
        print('taskSnapshot : ${taskSnapshot.storageMetadata}');
    
        if (uploadTask.isComplete) {
          var downloadUrl = await taskSnapshot.ref.getDownloadURL();
          var filename = await taskSnapshot.ref.getName();
          var filelocation = await taskSnapshot.ref.getPath();
          var bucket = await taskSnapshot.ref.getBucket();
          var token = downloadUrl.toString().split('=media&token=')[1];
    
          print('name: $filename');
          print('path_firebase: $filelocation');
    
          print('downloadUrl: $downloadUrl');
          print('bucket: $bucket');
          print('token : $token');
    
          await User_DatabaseService().imageData(
            title: filename, // Not sure what exactly is a title
            filename: filename,
            token: token,
            filelocation: filelocation,
            url: downloadUrl,
            created: 'created',
            creator_uid: userID,
            format: 'jpg',
            created_date: datetime,
            timestamp: timeStamp,
            tag_label: tag,
            user_tag: 'user_tag',
            rating: 0,
            like: 0,
            display_count: 0,
            participants: [],
            post_notification: false,
            score: 0,
          );
          return true;
        } else {
          return false;
        }
      }

Error message

Exception has occurred. FlutterError (setState() called after dispose(): _UploadPictureInfoState#65d68(lifecycle state: defunct, not mounted) This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree. This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().)

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Punreach Rany
  • 2,560
  • 7
  • 23
  • 56
  • 1
    You could have WillPopScope to ask them if they really want to exit. WillPopScope will detect if the user pressed the back button. If they wanted to exit, you could cancel your upload operation. – CoderUni Sep 23 '20 at 06:33
  • thank you! I would be even better if you can drop down some sample code. – Punreach Rany Sep 23 '20 at 07:38
  • I don't want to create duplicates for it. Here are other answers for using WillPopScope: https://stackoverflow.com/questions/45916658/how-to-deactivate-or-override-the-android-back-button-in-flutter . Return true to go back and return false to stop going back – CoderUni Sep 23 '20 at 08:16
  • 2
    Don't forget that the user can exit your app anytime while you are uploading. It would be better for you to use try catch to handle these. – CoderUni Sep 23 '20 at 08:37

0 Answers0