Search code examples
flutterauthenticationmethodsprogram-entry-point

How stay login after close App in Flutter?


I have an application that saves in the local storage of the device, making use of the glutton: ^2.0.0 in debug mode everything works fine but when I compile the APK, I run the application and close it from the application manager, when I rerun the application the logic of the Main method does not work.

Any ideas?

void main() async {

  //VARIABLES
  String jsonDatos='';
  String _defaultHome = '/loguin';
  
  //INTENTAR
  try { 

    //EXISTE LA VARIABLE
    bool isExist = await Glutton.have('logueado');

    //EXISTE LA VARIABLE
    if (isExist){  

      //OBTENER VALOR
      bool? logueado = await Glutton.vomit('logueado');

      //SI NO ES NUL NI FALSE 
      if (logueado==null || logueado==false) {

        //PAGINA DE LOGUEO              
        _defaultHome=  '/loguin';

      }else{//SI ES TRUE    

        //ASIGNAR VALOR
        jsonDatos=await Glutton.vomit('jsdatos');

        //PARSEADO DEL JSON
        final dynamic clsDatosUsuario= jsonDecode(jsonDatos);

        //SI TIENE COORDENADAS REGISTRADAS
        if (clsDatosUsuario[0]["LATITUD"]!=""){

          //PAGINA PRINCIPAL
          _defaultHome= '/principal';

        }else{

          //PAGINA DE COORDENADAS
          _defaultHome= '/terminostexto';

        }         

      }  

    //SI NOEXISTE LA VARIABLE
    }else{

      //PAGINA DE LOGUEO           
     _defaultHome='/loguin';

    }

  } catch (error) {//SI HA CAMBIADO EL KEY

    //PAGINA DE LOGUEO         
    _defaultHome= '/loguin';

  } //SI HA CAMBIADO EL KEY

  runApp(LoginUiApp(initialRoute: _defaultHome));

}

class LoginUiApp extends StatelessWidget {
  final String initialRoute;
  //COLORES DEL HEADER
  final Color _primaryColor = HexColor('#002981');
  final Color _accentColor = HexColor('#002981');
  //final Color _encabezadoTabla = HexColor('#002981');
    
 //COLOR PARA EL FOOTER
  final Color _footeColor = HexColor('#D50000');  

  LoginUiApp({Key? key, required this.initialRoute} ) : super(key: key);
  
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //MANEJO DE IDIOMAS
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate
      ],
      /*supportedLocales:const [
        Locale('en'),
        Locale('es')
      ],*/
      //MANEJO DE IDIOMAS
      //QUITAR DEBUB
      debugShowCheckedModeBanner: false,  
      //RUTAS
      routes: {
        '/loguin': (context) => const LoginPage(),
        '/terminos': (context) => const TerminosPage(),
        '/terminostexto': (context) => const TerminosTextoPage(),
        '/acerca': (context) => const AcercaPage(),
        '/contacto': (context) => const ContactoPage(),
        '/miubicacion': (context) => const MiUbicacionPage(),
        '/miubicacionmapa': (context) => const MiUbicacionMapaPage(),
        '/buscarfamilias': (context) => const BuscarFamiliasPage(),
        '/familiasencontradasmapa': (context) => const FamiliasEncontradasMapaPage(),
        '/principal': (context) =>  const PrincipalPage() ,        
        '/pagina2': (context) =>const Pagina2Page()
      },
      builder: OneContext().builder,
      navigatorKey: OneContext().key,
      title: 'CovoiturageLF',
      theme: ThemeData(
        primaryColor: _primaryColor,    
        secondaryHeaderColor: _footeColor,
        scaffoldBackgroundColor: Colors.grey.shade100, colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.grey).copyWith(secondary: _accentColor),               
      ),
      initialRoute: initialRoute,
      //home: const SplashPage(),
    );
  }

}```

Solution

  • add WidgetsFlutterBinding.ensureInitialized() as a first-line in your main

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      // your code
    

    if you want to understand why, checkout this link https://stackoverflow.com/a/63873689/12156637

    note that Glutton uses channel methods too