Flutter
Parse SDK (REST)
Integração Flutter e Back4App: Upload e Exibição de Arquivos
13 min
salvar arquivos de um app flutter introdução às vezes, as aplicações precisam armazenar dados que muitas vezes são grandes demais para serem armazenados dentro de um parseobject o caso de uso mais comum é armazenar imagens, mas você também pode usá lo para documentos, vídeos, músicas e outros dados binários para armazenar um arquivo no parse, você deve sempre associar o arquivo a outro objeto de dados para que você possa recuperar esse caminho de arquivo ao consultar o objeto se você não associar, o arquivo será armazenado, mas você não o encontrará na nuvem outra dica importante é dar um nome ao arquivo que tenha uma extensão de arquivo essa extensão permite que o parse descubra o tipo de arquivo e o manipule adequadamente também devemos mencionar que cada upload recebe um identificador único, então não há problema em fazer upload de vários arquivos usando o mesmo nome no flutter, parsefile e parsewebfile permitem que você armazene e recupere arquivos de aplicativo na nuvem este guia explica como armazenar e recuperar arquivos em seu app flutter para gerenciar o armazenamento em nuvem do back4app se você não associar seu arquivo a um objeto de dados, o arquivo se tornará um arquivo órfão e você não poderá encontrá lo na nuvem do back4app pré requisitos um app https //www back4app com/docs/get started/new parse app no back4app nota siga o https //www back4app com/docs/get started/new parse app para aprender como criar um app parse no back4app um app flutter conectado ao back4app nota siga o https //www back4app com/docs/flutter/parse sdk/parse flutter sdk para criar um projeto flutter conectado ao back4app um dispositivo (ou dispositivo virtual) rodando android ou ios para executar este exemplo do guia, você deve configurar o plugin https //pub dev/packages/image picker corretamente não se esqueça de adicionar permissões para ios a fim de acessar imagens armazenadas no dispositivo { btn target=” blank” rel=”nofollow”} leia atentamente as instruções para configurar o projeto android e ios objetivo criar um app de galeria flutter que faz upload e exibe imagens do back4app 1 compreendendo a classe parsefile e parsewebfile existem três classes de arquivo diferentes neste sdk parse para flutter parsefilebase parsefilebase é uma classe abstrata, a base de cada classe de arquivo que este sdk pode manipular parsefile parsefile estende parsefilebase parsefilebase e é, por padrão, usada como a classe de arquivo em todas as plataformas (não válida para web) esta classe usa um file file de dart\ io dart\ io para armazenar o arquivo bruto parsewebfile parsewebfile é o equivalente a parsefile parsefile usado no flutter web esta classe usa um uint8list uint8list para armazenar o arquivo bruto os métodos disponíveis em parsefilebase parsefilebase para manipular arquivos save() save() ou upload() upload() para salvar o arquivo na nuvem download() download() para recuperar o arquivo e armazená lo no armazenamento local existem propriedades para obter informações do arquivo salvo url url obtém a url do arquivo está disponível apenas após você salvar o arquivo ou após obter o arquivo de um parse object name name obtém o nome do arquivo este é o nome do arquivo dado pelo usuário antes de chamar o save() save() método após chamar o método, a propriedade recebe um identificador único 2 enviando uma imagem para enviar uma imagem, você só precisará criar uma parsefilebase parsefilebase instância e então chamar o save save método vamos fazer isso em nossa upload upload função 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(); o trecho acima cria e salva a imagem, e após a conclusão do salvamento, associamos a ela um parseobject parseobject chamado gallery gallery 1 final gallery = parseobject('gallery') 2 set('file', parsefile); 3 await gallery save(); 3 exibindo imagens para exibir imagens, você precisa obter a url da imagem para fazer o upload de uma imagem, você só precisará criar uma parsefilebase parsefilebase instância e então chamar o 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 fazer upload e recuperar do aplicativo flutter agora vamos usar nosso exemplo para fazer upload e exibir imagens no aplicativo flutter, com uma interface simples abra seu projeto flutter, vá para o main dart main dart arquivo, limpe todo o código e substitua o por 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 } encontre seu applicationid applicationid e client key client key credenciais navegando para o seu app dashboard >configurações >segurança e chaves em https //www back4app com/ atualize seu código em main dart main dart com ambos os valores do seu projeto applicationid applicationid e clientkey clientkey no back4app keyapplicationid = appid appid keyclientkey = client key client key execute o projeto, e o aplicativo será carregado como mostrado na imagem conclusão neste ponto, você fez o upload da imagem no back4app e a exibiu em um aplicativo flutter