Home > Mobile >  Shared Preferences in Flutter gives me error and is not working
Shared Preferences in Flutter gives me error and is not working

Time:09-27

So, I want to implement in my current project the feature where if I am not yet registered I will be directed to the intro slider page, login or signup page of my application. But when the user has already logged in, even if he/she exited the app, when she opens it again, he/she must be automatically logged in unless she signs out of the app. After thorough research, I saw a video where shared preferences is used to do this kind of action. I tried following the tutorial and here is my code:

import 'package:ehatid_driver_app/login.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'intro_slider.dart';
import 'package:firebase_core/firebase_core.dart';

 int initScreen;

Future <void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences preferences = await SharedPreferences.getInstance();
  initScreen = await preferences.getInt('initScreen');
  await preferences.setInt('initScreen', 1);
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp ({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        backgroundColor: Color(0xFFFED90F),
      ),
      initialRoute: initScreen == 0 || initScreen == null ? 'introslider' : 'login', // paltan ang login ng homepage
      routes: {
        'login' : (context) => LoginScreen(),
        'introslider' : (context) => IntroSliderPage(),
      },
    );
  }
}

However, I was not able to run this because of two errors which are:

The non-nullable variable 'initScreen' must be initialized.

A value of type 'int?' can't be assigned to a variable of type 'int'.

So, how will I be able to fix it? Any help will be much appreciated.

EDIT: Codes for Login

   Future signIn() async {
    await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: _emailController.text.trim(),
        password: _passwordController.text.trim(),
    ).whenComplete((){
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => const MainPage(),
        ),
      );
    });
  }

UPDATE: ERROR

Error

CodePudding user response:

You can use Integer initScreen; instead of int initScreen; , because Integer is nullable.

CodePudding user response:

You have to handle the null check and you are using a null value. Either set a default value to shared preference or while reading the shared pref, if it is null set a default value. Corrected code given below.

import 'package:ehatid_driver_app/login.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'intro_slider.dart';
import 'package:firebase_core/firebase_core.dart';

int? initScreen;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences preferences = await SharedPreferences.getInstance();

  initScreen = (preferences.getInt('initScreen')) ?? 0;
  await preferences.setInt('initScreen', 1);
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        backgroundColor: Color(0xFFFED90F),
      ),
      initialRoute: initScreen == 0
          ? 'introslider'
          : 'login', // paltan ang login ng homepage
      routes: {
        'login': (context) => LoginScreen(),
        'introslider': (context) => IntroSliderPage(),
      },
    );
  }
}
  • Related