skip to Main Content

i am creating a file as json for storing notes backup

here is the method for creating file,

before i write notes, it showing error in this method to opening a file

Future<void> writeNotesToFile() async {
  String path ='/storage/emulated/0/Android/data/com.example.noteapp/backup_note.json';
  File? file = File(path);
  print(path);
  bool doesFileExists = await file.exists();

  print(doesFileExists.toString());
  if (doesFileExists==false) {
     file.create();
  }
 
  
}

it was working fine…but when i uninstalled the app and installed again..its showing error while calling this method…I have not changed path

2

Answers


  1. Step 1: Check Permission: https://pub.dev/packages/permission_handler

    Step 2: Add this plugin to get the directory: https://pub.dev/packages/path_provider

    Use below code:

    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/backup_note.json');
    await file.create();
    
    Login or Signup to reply.
  2. You need to add storage permission to store any file in External storage.

    For this, you can use the permission_handler package.

    I am giving an example code of how you can get that permission.

    1. Add the permission_handler package to your pubspec.yaml file:

    permission_handler: ^9.0.0
    

    2. Update AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    

    3. Request the required permissions:

    import 'package:flutter/material.dart';
    import 'package:permission_handler/permission_handler.dart';
    
    Future<void> requestStoragePermission() async {
      if (await Permission.storage.request().isGranted) {
        // Call your writeNotesToFile() method here.
        writeNotesToFile();
      } else {
        // Permission is not granted.
      }
    }
    

    I hope this will work for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search