Category

Flutter Packages

Category

2 Flutter Path Provider Examples With Tutorial

flutter path provider example
In this post, you will learn about the Flutter path provider package.

Okay, what it actually does?

Using path_provider package, you can easily find the most used locations on the filesystem of the device. It supports both iOS and Android.

Path provider methods – getApplicationDocumentDirectory() to latest ones

You can use these 8 methods to access device storage.

  1. getApplicationDocumentsDirectory(): Gives path to the directory where Application can place it’s private files, Files only get wiped out when application itself removed.
    iOSNSDocumentsDirectory API.
    Android – returns AppData directory.
  2. 
    
      final directory = await getApplicationDocumentsDirectory();
    
    
    

  3. getTemporaryDirectory(): This gives path to the temporary directory in device. Files can be deleted at any time.
    iOS – It uses NSCachesDirectory API
    Android – Use getCacheDir API
  4. getExternalStorageDirectories: It returns list of path of directories where app’s specific data can be stored. Commonly, path lives in external storage partitions or SD cards. Now it’s only available in Android, So before use, it’s better to find out the operating system. on iOS, it shows UnSupportedError.
    Android: it returns Context.getExternalFilesDirs(String type).
    Below API 19: Context.getExternalFilesDir(String type).
  5. getExternalStorageDirectory(): Only available in Android. Provides path to External storage(Generally SD card).

    This does not support in iOS, it will throw UnSupportedError if you use it.

  6. getDownloadsDirectory(): It returns path of the directory where downloaded files get stored. Not available in Android and iOS, it gives UnSupportedError.
  7. getExternalCacheDirectories(): It returns list of path of directories where app’s external cache data get stored. Commonly, these types of paths lives in SD cards and only available in Android, better check it out which OS is running because iOS throws UnSupportedError.

    Android – returns Context.getExternalCacheDirs().
    Below API 19 : Context.getExternalCacheDir() API.

  8. getLibraryDirectory():It returns path of the directory where app store persistent data such as sqlite.db, Not available in Android.
  9. getApplicationSupportDirectory(): It returns the directory where app place support files. It’s not recommended to use for user data files.

    iOS – Uses NSApplicationSupportDirectory API.
    Android – Uses getFilesDir API.

Let’s make a simple Create and Read File example, that will help you to learn about it better.

Flutter Path Provider Example – Create File and Read

path_provider example - Create File
In this example, you will learn how to create a text file, input from TextField using path provider and print to Text widget.

So let’s create a Flutter project named flutter_path_provider_example.


dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.0
  path_provider: ^1.6.24

  • Open the project and pubspec.yaml, put path_provider package.


import 'package:flutter/material.dart';

void main() {
  runApp(PathProviderExample());
}

class PathProviderExample extends StatefulWidget {
  @override
  _PathProviderExampleState createState() => _PathProviderExampleState();
}

class _PathProviderExampleState extends State {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

  • type stful for StatefulWidget and provide name – PathProviderExample


   final textController = TextEditingController();
   String text;


  • Create textController instance to access input from TextField.
  • text variable for storing text from TextField.
  • Put both of them in the State class.


@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Path Provider Example',
    home: Scaffold(
      appBar: AppBar(
        title: Text('Flutter Path Provider Example'),
      ),
      body: Column(
        children: [
          Padding(
            padding:
                const EdgeInsets.symmetric(horizontal: 18.0, vertical: 10),
            child: TextField(
              textAlign: TextAlign.center,//input aligns to center
              controller: textController,//assigns TextEditingController
            ),
          ),
          SizedBox(
            height: 10,
          ),
          ElevatedButton(
            child: Text('Create File'),
            onPressed: () => createFile(textController.text),//calls createFile() when //button pressed
          ),
          ElevatedButton(
            onPressed: () async {
              await readFile();//calls readFile()
              setState(() {});//rebuilds the UI.
            },
            child: Text('Read File'),
          ),
          SizedBox(
            height: 20,
          ),
          if (text != null) Text('$text')//text set if it's not null.
        ],
      ),
    ),
  );
}

  • Using Scaffold, simply make structure of the app.
  • Column arranges widget in vertical order.
  • Padding widget provides empty space around the TextField.
  • SizedBox gives some space between Widgets.
  • ElevatedButton is latest button provided by Flutter. (RaisedButton – obsolete now).

Let’s create createFile() method now.


Future createFile(String text) async {
//provides directory path.
    final directory = await getApplicationDocumentsDirectory();
//creates text_file in the provided path.
    final file = File('${directory.path}/text_file.txt');
    await file.writeAsString(text);
  }

  • import below statements to avoid red squiqqly lines:
    • import ‘dart:io’; – importing File class and methods.
    • import ‘package:path_provider/path_provider.dart’; – getApplicationDocumentsDirectory()
  • This is an asynchrononus method, so we need to use await and async keyword.
  • Input from the TextField is written to the text file.

just like createFile, make readFile() method.


Future readFile() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/text_file.txt');
      text = await file.readAsString();
    } catch (e) {
      print('exception');
    }
  }

  • text_file is read using readAsString() method.

Don’t forget to dispose TextEditingController.


    @override
  void dispose() {
    textController.dispose();
    super.dispose();
  }


Where files get stored when using getApplicationDocumentsDirectory() in Flutter?

Let’s check it out where is text_file get stored that we created in above example.

device file explorer android studio

Using Android Studio, View -> Tool Windows -> Device File Explorer.

text file location in path provider

Go for this location /data/data/com.androidride.flutter_path_provider_example/app_flutter/text_file.txt

Flutter Create Directory Example

flutter create directory example - path provider

In this flutter path provider example, you will learn how to create a directory using Path Provider package.

Just like the First Example, create a Flutter project and put path_provider pacakage in pubspec.yaml.

open main.dart and clear everything and type stless for StatelessWidget.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget 
{
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}


Before creating UI, let’s create createDir() method which creates directory.



  createDir() async {
    final directoryName = 'AndroidRide';
    final docDir = await getApplicationDocumentsDirectory();
    final myDir = Directory('${docDir.path}/$directoryName');

    if (await myDir.exists()) {
      print(myDir.path);
    }

    final dir = await myDir.create(recursive: true);
    print(dir.path);
  }

  • Import these:
    • import ‘dart:io’;

    • import ‘package:path_provider/path_provider.dart’;

Let’s complete the UI.


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Create New Directory Example'),
        ),
        body: Container(
          padding: EdgeInsets.all(20.0),
          alignment: Alignment.topCenter,
          child: ElevatedButton(
            child: Text('Create Directory'),
            onPressed: () {
              createDir();
            },
          ),
        ),
      ),
    );
  }



The directory gets created when you tap on the “Create Directory” Button. Check it out the directory using Device File Explorer.

flutter create new directory example - path provider

That’s all for now.

More Information: path_provider