Flutter
Parse SDK (REST)
Subir y mostrar archivos en Flutter con Parse y Back4App
13 min
guardar archivos de una aplicación flutter introducción a veces las aplicaciones necesitan almacenar datos que a menudo son demasiado grandes para ser almacenados dentro de un parseobject el caso de uso más común es almacenar imágenes, pero también puedes usarlo para documentos, videos, música y otros datos binarios para almacenar un archivo en parse, siempre debes asociar el archivo con otro objeto de datos para que puedas recuperar esta ruta de archivo al consultar el objeto si no asocias, el archivo se almacenará, pero no podrás encontrarlo en la nube otro consejo importante es darle un nombre al archivo que tenga una extensión de archivo esta extensión permite a parse determinar el tipo de archivo y manejarlo en consecuencia también debemos mencionar que cada carga recibe un identificador único, por lo que no hay problema en cargar múltiples archivos usando el mismo nombre en flutter, parsefile y parsewebfile te permiten almacenar y recuperar archivos de aplicación en la nube esta guía explica cómo almacenar y recuperar archivos en tu aplicación flutter para gestionar el almacenamiento en la nube de back4app si no asocias tu archivo a un objeto de datos, el archivo se convertirá en un archivo huérfano y no podrás encontrarlo en back4app cloud requisitos previos una aplicación creada en back4app nota sigue el tutorial de nueva aplicación parse para aprender a crear una aplicación parse en back4app una aplicación flutter conectada a back4app nota sigue el instalar parse sdk en el proyecto flutter para crear un proyecto flutter conectado a back4app un dispositivo (o dispositivo virtual) que ejecute android o ios para ejecutar este ejemplo de guía, debes configurar el plugin image picker correctamente no olvides agregar permisos para ios para acceder a las imágenes almacenadas en el dispositivo { btn target=” blank” rel=”nofollow”} lee cuidadosamente las instrucciones para configurar el proyecto de android e ios objetivo crea una aplicación de galería flutter que suba y muestre imágenes desde back4app 1 entendiendo la clase parsefile y parsewebfile hay tres clases de archivos diferentes en este sdk de parse para flutter parsefilebase parsefilebase es una clase abstracta, la base de cada clase de archivo que este sdk puede manejar parsefile parsefile extiende parsefilebase parsefilebase y se utiliza por defecto como la clase de archivo en cada plataforma (no válido para web) esta clase utiliza un file file de dart\ io dart\ io para almacenar el archivo en bruto parsewebfile parsewebfile es el equivalente a parsefile parsefile utilizado en flutter web esta clase utiliza un uint8list uint8list para almacenar el archivo en bruto los métodos disponibles en parsefilebase parsefilebase para manipular archivos save() save() o upload() upload() para guardar el archivo en la nube download() download() para recuperar el archivo y almacenarlo en el almacenamiento local hay propiedades para obtener información del archivo guardado url url obtiene la url del archivo solo está disponible después de guardar el archivo o después de obtener el archivo de un parse object name name obtiene el nombre del archivo este es el nombre de archivo dado por el usuario antes de llamar al save() save() método después de llamar al método, la propiedad recibe un identificador único 2 subiendo una imagen para subir una imagen, solo necesitarás crear una parsefilebase parsefilebase instancia y luego llamar al save save método hagamos eso en nuestra upload upload función 1 parsefilebase? parsefile; 2 3 if (kisweb) { 4 //flutter web 5 parsefile = parsewebfile( 6 await pickedfile! readasbytes(), 7 name 'image jpg'); //name for file is required 8 } else { 9 //flutter mobile/desktop 10 parsefile = parsefile(file(pickedfile! path)); 11 } 12 await parsefile save(); el fragmento anterior crea y guarda la imagen, y después de que se complete el guardado, la asociamos con un parseobject parseobject llamado gallery gallery 1 final gallery = parseobject('gallery') 2 set('file', parsefile); 3 await gallery save(); 3 mostrando imágenes para mostrar imágenes, necesitas obtener la url de la imagen para subir una imagen, solo necesitarás crear una parsefilebase parsefilebase instancia y luego llamar al save save método 1 parsefilebase? varfile = parseobject get\<parsefilebase>('file'); 2 3 return image network( 4 varfile! url!, 5 width 200, 6 height 200, 7 fit boxfit fitheight, 8 ); 4 subir y recuperar desde la aplicación flutter ahora usemos nuestro ejemplo para subir y mostrar imágenes en la aplicación flutter, con una interfaz simple abre tu proyecto de flutter, ve al main dart main dart archivo, limpia todo el código y reemplázalo con 1 import 'dart\ io'; 2 3 import 'package\ flutter/cupertino dart'; 4 import 'package\ flutter/foundation dart'; 5 import 'package\ flutter/material dart'; 6 import 'package\ image picker/image picker dart'; 7 import 'package\ parse server sdk flutter/parse server sdk dart'; 8 9 void main() async { 10 widgetsflutterbinding ensureinitialized(); 11 12 final keyapplicationid = 'your app id here'; 13 final keyclientkey = 'your client key here'; 14 15 final keyparseserverurl = 'https //parseapi back4app com'; 16 17 await parse() initialize(keyapplicationid, keyparseserverurl, 18 clientkey keyclientkey, debug true); 19 20 runapp(materialapp( 21 title 'flutter storage file', 22 debugshowcheckedmodebanner false, 23 home homepage(), 24 )); 25 } 26 27 class homepage extends statefulwidget { 28 @override 29 homepagestate createstate() => homepagestate(); 30 } 31 32 class homepagestate extends state\<homepage> { 33 pickedfile? pickedfile; 34 35 list\<parseobject> results = \<parseobject>\[]; 36 double selecteddistance = 3000; 37 38 @override 39 widget build(buildcontext context) { 40 return scaffold( 41 body padding( 42 padding const edgeinsets all(16 0), 43 child column( 44 crossaxisalignment crossaxisalignment stretch, 45 children \[ 46 container( 47 height 200, 48 child image network( 49 'https //blog back4app com/wp content/uploads/2017/11/logo b4a 1 768x175 1 png'), 50 ), 51 sizedbox( 52 height 16, 53 ), 54 center( 55 child const text('flutter on back4app save file', 56 style textstyle(fontsize 18, fontweight fontweight bold)), 57 ), 58 sizedbox( 59 height 16, 60 ), 61 container( 62 height 50, 63 child elevatedbutton( 64 child text('upload file'), 65 style elevatedbutton stylefrom(primary colors blue), 66 onpressed () { 67 navigator push( 68 context, 69 materialpageroute(builder (context) => savepage()), 70 ); 71 }, 72 ), 73 ), 74 sizedbox( 75 height 8, 76 ), 77 container( 78 height 50, 79 child elevatedbutton( 80 child text('display file'), 81 style elevatedbutton stylefrom(primary colors blue), 82 onpressed () { 83 navigator push( 84 context, 85 materialpageroute(builder (context) => displaypage()), 86 ); 87 }, 88 )) 89 ], 90 ), 91 )); 92 } 93 } 94 95 class savepage extends statefulwidget { 96 @override 97 savepagestate createstate() => savepagestate(); 98 } 99 100 class savepagestate extends state\<savepage> { 101 pickedfile? pickedfile; 102 bool isloading = false; 103 104 @override 105 widget build(buildcontext context) { 106 return scaffold( 107 appbar appbar( 108 title text('upload fie'), 109 ), 110 body padding( 111 padding const edgeinsets all(12 0), 112 child column( 113 crossaxisalignment crossaxisalignment stretch, 114 children \[ 115 sizedbox(height 16), 116 gesturedetector( 117 child pickedfile != null 118 ? container( 119 width 250, 120 height 250, 121 decoration 122 boxdecoration(border border all(color colors blue)), 123 child kisweb 124 ? image network(pickedfile! path) 125 image file(file(pickedfile! path))) 126 container( 127 width 250, 128 height 250, 129 decoration 130 boxdecoration(border border all(color colors blue)), 131 child center( 132 child text('click here to pick image from gallery'), 133 ), 134 ), 135 ontap () async { 136 pickedfile? image = 137 await imagepicker() getimage(source imagesource gallery); 138 139 if (image != null) { 140 setstate(() { 141 pickedfile = image; 142 }); 143 } 144 }, 145 ), 146 sizedbox(height 16), 147 container( 148 height 50, 149 child elevatedbutton( 150 child text('upload file'), 151 style elevatedbutton stylefrom(primary colors blue), 152 onpressed isloading || pickedfile == null 153 ? null 154 () async { 155 setstate(() { 156 isloading = true; 157 }); 158 parsefilebase? parsefile; 159 160 if (kisweb) { 161 //flutter web 162 parsefile = parsewebfile( 163 await pickedfile! readasbytes(), 164 name 'image jpg'); //name for file is required 165 } else { 166 //flutter mobile/desktop 167 parsefile = parsefile(file(pickedfile! path)); 168 } 169 await parsefile save(); 170 171 final gallery = parseobject('gallery') 172 set('file', parsefile); 173 await gallery save(); 174 175 setstate(() { 176 isloading = false; 177 pickedfile = null; 178 }); 179 180 scaffoldmessenger of(context) 181 removecurrentsnackbar() 182 showsnackbar(snackbar( 183 content text( 184 'save file with success on back4app', 185 style textstyle( 186 color colors white, 187 ), 188 ), 189 duration duration(seconds 3), 190 backgroundcolor colors blue, 191 )); 192 }, 193 )) 194 ], 195 ), 196 ), 197 ); 198 } 199 } 200 201 class displaypage extends statefulwidget { 202 @override 203 displaypagestate createstate() => displaypagestate(); 204 } 205 206 class displaypagestate extends state\<displaypage> { 207 @override 208 widget build(buildcontext context) { 209 return scaffold( 210 appbar appbar( 211 title text("display gallery"), 212 ), 213 body futurebuilder\<list\<parseobject>>( 214 future getgallerylist(), 215 builder (context, snapshot) { 216 switch (snapshot connectionstate) { 217 case connectionstate none 218 case connectionstate waiting 219 return center( 220 child container( 221 width 100, 222 height 100, 223 child circularprogressindicator()), 224 ); 225 default 226 if (snapshot haserror) { 227 return center( 228 child text("error "), 229 ); 230 } else { 231 return listview\ builder( 232 padding const edgeinsets only(top 8), 233 itemcount snapshot data! length, 234 itembuilder (context, index) { 235 //web/mobile/desktop 236 parsefilebase? varfile = 237 snapshot data!\[index] get\<parsefilebase>('file'); 238 239 //only ios/android/desktop 240 / 241 parsefile? varfile = 242 snapshot data!\[index] get\<parsefile>('file'); 243 / 244 return image network( 245 varfile! url!, 246 width 200, 247 height 200, 248 fit boxfit fitheight, 249 ); 250 }); 251 } 252 } 253 }), 254 ); 255 } 256 257 future\<list\<parseobject>> getgallerylist() async { 258 querybuilder\<parseobject> querypublisher = 259 querybuilder\<parseobject>(parseobject('gallery')) 260 orderbyascending('createdat'); 261 final parseresponse apiresponse = await querypublisher query(); 262 263 if (apiresponse success && apiresponse results != null) { 264 return apiresponse results as list\<parseobject>; 265 } else { 266 return \[]; 267 } 268 } 269 } encuentra tu applicationid applicationid y client key client key credenciales navegando a tu app dashboard >settings >security and keys en back4app website https //www back4app com/ actualiza tu código en main dart main dart con ambos valores de tu proyecto applicationid applicationid y clientkey clientkey en back4app keyapplicationid = appid appid keyclientkey = client key client key ejecuta el proyecto, y la aplicación se cargará como se muestra en la imagen conclusión en este punto, has subido una imagen en back4app y la has mostrado en una aplicación flutter