Flutter

Save Files from a Flutter App

Introduction

Sometimes applications need to store data that is often too large to be stored inside a ParseObject. The most common use case is storing images, but you can also use it for documents, videos, music, and other binary data.

To store a file on Parse, you should always associate the file with another data object so you can retrieve this file path when querying the object. If you do not associate, the file will be stored, but you will not find them on the Cloud.
Another important tip is to give a name to the file that has a file extension. This extension lets Parse figure out the file type and handle it accordingly. We should also mention that each upload gets a unique identifier, so there’s no problem uploading multiple files using the same name.

In Flutter, ParseFile and ParseWebFile let you store and retrieve application files in the Cloud that would. This guide explains how to store and retrieve files in your Flutter App to manage Back4app cloud storage.

  • If you do not associate your file to a data object the file will become an orphan file and you wont be able to find it on Back4App Cloud.

Prerequisites

To complete this tutorial, you will need:

  • Android Studio or VS Code installed (with Plugins Dart and Flutter)

  • An app created on Back4App.
  • An Flutter app connected to Back4app.
  • A device (or virtual device) running Android or iOS.
  • In order to run this guide example you should set up the plugin image_picker properly. Do not forget to add permissions for iOS in order to access images stored in device. {: .btn target=”_blank” rel=”nofollow”}. Carefully read the instructions for setting up the Android and iOS project.

Goal

Create an Flutter Gallery App that uploads and displays images from Back4app.

Step 1 - Understanding ParseFile and ParseWebFile class

There are three different file classes in this Parse SDK for Flutter

  • ParseFileBase is an abstract class, the foundation of every file class that this SDK can handle.
  • ParseFile extends ParseFileBase and is by default used as the file class on every platform (not valid for web). This class uses a File from dart:io for storing the raw file.
  • ParseWebFile is the equivalent to ParseFile used at Flutter Web. This class uses an Uint8List for storing the raw file.

The methods available on ParseFileBase to manipulate files:

  • save() or upload() for save file on Cloud
  • download() for retrive file and store in local storage

There are properties to get information from the saved file:

  • url: Gets the file url. It is only available after you save the file or after you get the file from a Parse.Object.
  • name: Gets the file name. This is the filename given by the user before calling the save() method. After callint the method, the property receives a unique identifier.

Step 2 - Uploading an Image

To upload an image, you will only need to create a ParseFileBase instance and then call the save method.

Let’s do that in our upload function:

1
2
3
4
5
6
7
8
9
10
11
12
      ParseFileBase? parseFile;

      if (kIsWeb) {
        //Flutter Web
        parseFile = ParseWebFile(
            await pickedFile!.readAsBytes(),
            name: 'image.jpg'); //Name for file is required
      } else {
        //Flutter Mobile/Desktop
        parseFile = ParseFile(File(pickedFile!.path));
      }
      await parseFile.save();

The above snippet creates and saves the image, and after the save completes, we associate it with a ParseObject called Gallery.

1
2
3
      final gallery = ParseObject('Gallery')
        ..set('file', parseFile);
      await gallery.save();

Step 3 - Displaying Images

To display images, you need to get the image’s URL.

To upload an image, you will only need to create a ParseFileBase instance and then call the save method.

1
2
3
4
5
6
7
8
    ParseFileBase? varFile = parseObject.get<ParseFileBase>('file');

    return Image.network(
      varFile!.url!,
      width: 200,
      height: 200,
      fit: BoxFit.fitHeight,
    );

Step 4 - Upload and Retrieve from Flutter App

Let’s now use our example for uploading and displaying images in Flutter App, with a simple interface.

Open your Flutter project, go to the main.dart file, clean up all the code, and replace it with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final keyApplicationId = 'YOUR_APP_ID_HERE';
  final keyClientKey = 'YOUR_CLIENT_KEY_HERE';

  final keyParseServerUrl = 'https://parseapi.back4app.com';

  await Parse().initialize(keyApplicationId, keyParseServerUrl,
      clientKey: keyClientKey, debug: true);

  runApp(MaterialApp(
    title: 'Flutter - Storage File',
    debugShowCheckedModeBanner: false,
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  PickedFile? pickedFile;

  List<ParseObject> results = <ParseObject>[];
  double selectedDistance = 3000;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: 200,
            child: Image.network(
                'https://blog.back4app.com/wp-content/uploads/2017/11/logo-b4a-1-768x175-1.png'),
          ),
          SizedBox(
            height: 16,
          ),
          Center(
            child: const Text('Flutter on Back4app - Save File',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
          ),
          SizedBox(
            height: 16,
          ),
          Container(
            height: 50,
            child: ElevatedButton(
              child: Text('Upload File'),
              style: ElevatedButton.styleFrom(primary: Colors.blue),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => SavePage()),
                );
              },
            ),
          ),
          SizedBox(
            height: 8,
          ),
          Container(
              height: 50,
              child: ElevatedButton(
                child: Text('Display File'),
                style: ElevatedButton.styleFrom(primary: Colors.blue),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => DisplayPage()),
                  );
                },
              ))
        ],
      ),
    ));
  }
}

class SavePage extends StatefulWidget {
  @override
  _SavePageState createState() => _SavePageState();
}

class _SavePageState extends State<SavePage> {
  PickedFile? pickedFile;
  bool isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Upload Fie'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            SizedBox(height: 16),
            GestureDetector(
              child: pickedFile != null
                  ? Container(
                      width: 250,
                      height: 250,
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.blue)),
                      child: kIsWeb
                          ? Image.network(pickedFile!.path)
                          : Image.file(File(pickedFile!.path)))
                  : Container(
                      width: 250,
                      height: 250,
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.blue)),
                      child: Center(
                        child: Text('Click here to pick image from Gallery'),
                      ),
                    ),
              onTap: () async {
                PickedFile? image =
                    await ImagePicker().getImage(source: ImageSource.gallery);

                if (image != null) {
                  setState(() {
                    pickedFile = image;
                  });
                }
              },
            ),
            SizedBox(height: 16),
            Container(
                height: 50,
                child: ElevatedButton(
                  child: Text('Upload file'),
                  style: ElevatedButton.styleFrom(primary: Colors.blue),
                  onPressed: isLoading || pickedFile == null
                      ? null
                      : () async {
                          setState(() {
                            isLoading = true;
                          });
                          ParseFileBase? parseFile;

                          if (kIsWeb) {
                            //Flutter Web
                            parseFile = ParseWebFile(
                                await pickedFile!.readAsBytes(),
                                name: 'image.jpg'); //Name for file is required
                          } else {
                            //Flutter Mobile/Desktop
                            parseFile = ParseFile(File(pickedFile!.path));
                          }
                          await parseFile.save();

                          final gallery = ParseObject('Gallery')
                            ..set('file', parseFile);
                          await gallery.save();

                          setState(() {
                            isLoading = false;
                            pickedFile = null;
                          });

                          ScaffoldMessenger.of(context)
                            ..removeCurrentSnackBar()
                            ..showSnackBar(SnackBar(
                              content: Text(
                                'Save file with success on Back4app',
                                style: TextStyle(
                                  color: Colors.white,
                                ),
                              ),
                              duration: Duration(seconds: 3),
                              backgroundColor: Colors.blue,
                            ));
                        },
                ))
          ],
        ),
      ),
    );
  }
}

class DisplayPage extends StatefulWidget {
  @override
  _DisplayPageState createState() => _DisplayPageState();
}

class _DisplayPageState extends State<DisplayPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Display Gallery"),
      ),
      body: FutureBuilder<List<ParseObject>>(
          future: getGalleryList(),
          builder: (context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return Center(
                  child: Container(
                      width: 100,
                      height: 100,
                      child: CircularProgressIndicator()),
                );
              default:
                if (snapshot.hasError) {
                  return Center(
                    child: Text("Error..."),
                  );
                } else {
                  return ListView.builder(
                      padding: const EdgeInsets.only(top: 8),
                      itemCount: snapshot.data!.length,
                      itemBuilder: (context, index) {
                        //Web/Mobile/Desktop
                        ParseFileBase? varFile =
                            snapshot.data![index].get<ParseFileBase>('file');

                        //Only iOS/Android/Desktop
                        /*
                        ParseFile? varFile =
                            snapshot.data![index].get<ParseFile>('file');
                        */
                        return Image.network(
                          varFile!.url!,
                          width: 200,
                          height: 200,
                          fit: BoxFit.fitHeight,
                        );
                      });
                }
            }
          }),
    );
  }

  Future<List<ParseObject>> getGalleryList() async {
    QueryBuilder<ParseObject> queryPublisher =
        QueryBuilder<ParseObject>(ParseObject('Gallery'))
          ..orderByAscending('createdAt');
    final ParseResponse apiResponse = await queryPublisher.query();

    if (apiResponse.success && apiResponse.results != null) {
      return apiResponse.results as List<ParseObject>;
    } else {
      return [];
    }
  }
}

Find your ApplicationId and Client Key credentials navigating to your app Dashboard->Settings->Security and Keys at Back4App Website.

Update your code in main.dart with BOTH values of your project’s ApplicationId and ClientKey in Back4app.

  • keyApplicationId = App Id
  • keyClientKey = Client Key

Run the project, and the app will load as shown in the image.

flutter-back4app-files-1

flutter-back4app-files-1

flutter-back4app-files-1

flutter-back4app-files-1

Conclusion

At this point, you have uploaded image on Back4App and displayed it in a Flutter application.