Flutter
...
Third party Authentication
Integración de Inicio de Sesión con Apple en Flutter y Parse
10 min
flutter iniciar sesión con apple en parse introducción parse server admite autenticación de terceros en esta guía, aprenderás cómo soportar iniciar sesión con apple en tu aplicación flutter en parse requisitos previos para completar este tutorial, necesitarás flutter versión 2 2 x o posterior https //flutter dev/docs/get started/install android studio https //developer android com/studio o vs code instalado (con plugins dart y flutter) una aplicación flutter creada y conectada a back4app nota sigue el tutorial de nueva aplicación parse para aprender cómo crear una aplicación parse en back4app membresía paga al programa de desarrolladores de apple configura el plugin sign in with apple sign in with apple en el proyecto un dispositivo (no simulador) que ejecute ios objetivo iniciar sesión con apple en la aplicación flutter en el servidor parse 1 agrega la capacidad de iniciar sesión con apple a tu proyecto base de ios abre ios/runner xcworkspace ios/runner xcworkspace en xcode revisa las instrucciones del plugin sign in with apple sign in with apple para configurar iniciar sesión con apple iniciar sesión con apple en tu proyecto de ios selecciona equipo equipo para el proyecto guarda y cierra xcode 2 configurar el id de la aplicación en el portal de desarrolladores inicie sesión en su cuenta de desarrollador de apple https //developer apple com/ y vaya a la identificadores identificadores sección verifique si su identificador de paquete identificador de paquete creado está allí haga clic en el identificador de paquete identificador de paquete y desplácese hacia abajo verifique si el iniciar sesión con apple iniciar sesión con apple está seleccionado haga clic en editar editar y asegúrese de que el habilitar como un id de aplicación principal habilitar como un id de aplicación principal esté seleccionado si todo está bien, guarde y salga 3 configurar parse auth para apple ve al sitio web de back4app, inicia sesión y luego encuentra tu aplicación después de eso, haz clic en configuración del servidor configuración del servidor y busca el inicio de sesión con apple inicio de sesión con apple bloque y selecciona configuraciones configuraciones la inicio de sesión con apple inicio de sesión con apple sección se ve así ahora, solo necesitas pegar tu id de paquete id de paquete en el campo de abajo y hacer clic en el botón para guardar en caso de que enfrentes algún problema al integrar el inicio de sesión con apple, ¡por favor contacta a nuestro equipo a través del chat! 4 agregar el inicio de sesión con apple ahora que tienes el proyecto configurado, podemos obtener los datos del usuario e iniciar sesión en parse según la documentación, debemos enviar un mapa con los datos de autenticación del usuario 1 final credential = await signinwithapple getappleidcredential( 2 scopes \[ 3 appleidauthorizationscopes email, 4 appleidauthorizationscopes fullname, 5 ], 6 ); 7 8 //https //docs parseplatform org/parse server/guide/#apple authdata 9 //according to the documentation, we must send a map with user authentication data 10 //make sign in with apple 11 final parseresponse = await parseuser loginwith('apple', 12 apple(credential identitytoken!, credential useridentifier!)); 5 iniciar sesión con apple desde flutter ahora usemos nuestro ejemplo para iniciar sesión con apple en una aplicación flutter, con una interfaz simple abre tu proyecto flutter, ve al archivo main dart, limpia todo el código y reemplázalo con 1 import 'package\ flutter/material dart'; 2 import 'package\ parse server sdk flutter/parse server sdk dart'; 3 import 'package\ sign in with apple/sign in with apple dart'; 4 5 void main() async { 6 widgetsflutterbinding ensureinitialized(); 7 8 final keyapplicationid = 'your app id here'; 9 final keyclientkey = 'your client key here'; 10 final keyparseserverurl = 'https //parseapi back4app com'; 11 12 await parse() initialize(keyapplicationid, keyparseserverurl, 13 clientkey keyclientkey, debug true); 14 15 runapp(myapp()); 16 } 17 18 class myapp extends statelesswidget { 19 future\<bool> hasuserlogged() async { 20 parseuser? currentuser = await parseuser currentuser() as parseuser?; 21 if (currentuser == null) { 22 return false; 23 } 24 //checks whether the user's session token is valid 25 final parseresponse? parseresponse = 26 await parseuser getcurrentuserfromserver(currentuser sessiontoken!); 27 28 if (parseresponse? success == null || !parseresponse! success) { 29 //invalid session logout 30 await currentuser logout(); 31 return false; 32 } else { 33 return true; 34 } 35 } 36 37 @override 38 widget build(buildcontext context) { 39 return materialapp( 40 title 'flutter sign in with apple', 41 theme themedata( 42 primaryswatch colors blue, 43 visualdensity visualdensity adaptiveplatformdensity, 44 ), 45 home futurebuilder\<bool>( 46 future hasuserlogged(), 47 builder (context, snapshot) { 48 switch (snapshot connectionstate) { 49 case connectionstate none 50 case connectionstate waiting 51 return scaffold( 52 body center( 53 child container( 54 width 100, 55 height 100, 56 child circularprogressindicator()), 57 ), 58 ); 59 default 60 if (snapshot hasdata && snapshot data!) { 61 return userpage(); 62 } else { 63 return homepage(); 64 } 65 } 66 }), 67 ); 68 } 69 } 70 71 class homepage extends statefulwidget { 72 @override 73 homepagestate createstate() => homepagestate(); 74 } 75 76 class homepagestate extends state\<homepage> { 77 @override 78 widget build(buildcontext context) { 79 return scaffold( 80 appbar appbar( 81 title const text('flutter sign in with apple'), 82 ), 83 body center( 84 child singlechildscrollview( 85 padding const edgeinsets all(8), 86 child column( 87 crossaxisalignment crossaxisalignment stretch, 88 children \[ 89 container( 90 height 200, 91 child image network( 92 'http //blog back4app com/wp content/uploads/2017/11/logo b4a 1 768x175 1 png'), 93 ), 94 center( 95 child const text('flutter on back4app', 96 style 97 textstyle(fontsize 18, fontweight fontweight bold)), 98 ), 99 sizedbox( 100 height 100, 101 ), 102 container( 103 height 50, 104 child elevatedbutton( 105 child const text('sign in with apple'), 106 onpressed () => dosigninapple(), 107 ), 108 ), 109 sizedbox( 110 height 16, 111 ), 112 ], 113 ), 114 ), 115 )); 116 } 117 118 void dosigninapple() async { 119 late parseresponse parseresponse; 120 try { 121 //set scope 122 final credential = await signinwithapple getappleidcredential( 123 scopes \[ 124 appleidauthorizationscopes email, 125 appleidauthorizationscopes fullname, 126 ], 127 ); 128 129 //https //docs parseplatform org/parse server/guide/#apple authdata 130 //according to the documentation, we must send a map with user authentication data 131 //make sign in with apple 132 parseresponse = await parseuser loginwith('apple', 133 apple(credential identitytoken!, credential useridentifier!)); 134 135 if (parseresponse success) { 136 final parseuser parseuser = await parseuser currentuser() as parseuser; 137 138 //additional information in user 139 if (credential email != null) { 140 parseuser emailaddress = credential email; 141 } 142 if (credential givenname != null && credential familyname != null) { 143 parseuser set\<string>( 144 'name', '${credential givenname} ${credential familyname}'); 145 } 146 parseresponse = await parseuser save(); 147 if (parseresponse success) { 148 message showsuccess( 149 context context, 150 message 'user was successfully with sign in apple!', 151 onpressed () async { 152 navigator pushandremoveuntil( 153 context, 154 materialpageroute(builder (context) => userpage()), 155 (route\<dynamic> route) => false, 156 ); 157 }); 158 } else { 159 message showerror( 160 context context, message parseresponse error! message); 161 } 162 } else { 163 message showerror( 164 context context, message parseresponse error! message); 165 } 166 } on exception catch (e) { 167 print(e tostring()); 168 message showerror(context context, message e tostring()); 169 } 170 } 171 } 172 173 class userpage extends statelesswidget { 174 future\<parseuser?> getuser() async { 175 return await parseuser currentuser() as parseuser?; 176 } 177 178 @override 179 widget build(buildcontext context) { 180 void douserlogout() async { 181 final currentuser = await parseuser currentuser() as parseuser; 182 var response = await currentuser logout(); 183 if (response success) { 184 message showsuccess( 185 context context, 186 message 'user was successfully logout!', 187 onpressed () { 188 navigator pushandremoveuntil( 189 context, 190 materialpageroute(builder (context) => homepage()), 191 (route\<dynamic> route) => false, 192 ); 193 }); 194 } else { 195 message showerror(context context, message response error! message); 196 } 197 } 198 199 return scaffold( 200 appbar appbar( 201 title text('flutter sign in with apple'), 202 ), 203 body futurebuilder\<parseuser?>( 204 future getuser(), 205 builder (context, snapshot) { 206 switch (snapshot connectionstate) { 207 case connectionstate none 208 case connectionstate waiting 209 return center( 210 child container( 211 width 100, 212 height 100, 213 child circularprogressindicator()), 214 ); 215 default 216 return padding( 217 padding const edgeinsets all(8 0), 218 child column( 219 crossaxisalignment crossaxisalignment stretch, 220 mainaxisalignment mainaxisalignment center, 221 children \[ 222 center( 223 child text( 224 'hello, ${snapshot data! get\<string>('name')}')), 225 sizedbox( 226 height 16, 227 ), 228 container( 229 height 50, 230 child elevatedbutton( 231 child const text('logout'), 232 onpressed () => douserlogout(), 233 ), 234 ), 235 ], 236 ), 237 ); 238 } 239 })); 240 } 241 } 242 243 class message { 244 static void showsuccess( 245 {required buildcontext context, 246 required string message, 247 voidcallback? onpressed}) { 248 showdialog( 249 context context, 250 builder (buildcontext context) { 251 return alertdialog( 252 title const text("success!"), 253 content text(message), 254 actions \<widget>\[ 255 new elevatedbutton( 256 child const text("ok"), 257 onpressed () { 258 navigator of(context) pop(); 259 if (onpressed != null) { 260 onpressed(); 261 } 262 }, 263 ), 264 ], 265 ); 266 }, 267 ); 268 } 269 270 static void showerror( 271 {required buildcontext context, 272 required string message, 273 voidcallback? onpressed}) { 274 showdialog( 275 context context, 276 builder (buildcontext context) { 277 return alertdialog( 278 title const text("error!"), 279 content text(message), 280 actions \<widget>\[ 281 new elevatedbutton( 282 child const text("ok"), 283 onpressed () { 284 navigator of(context) pop(); 285 if (onpressed != null) { 286 onpressed(); 287 } 288 }, 289 ), 290 ], 291 ); 292 }, 293 ); 294 } 295 } encuentra tu id de aplicación y las credenciales de clave de cliente navegando a tu panel de control de la aplicación en sitio web de back4app https //www back4app com/ actualiza tu código en main dart main dart con los valores de applicationid y clientkey de tu proyecto en back4app keyapplicationid = id de la aplicación id de la aplicación keyclientkey = clave del cliente clave del cliente ejecuta el proyecto, y la aplicación se cargará como se muestra en la imagen conclusión en esta etapa, puedes usar iniciar sesión con apple en flutter en back4app