0

I want to store basic user data (name and email) in my flutter app (using shared preferences) and I want to use this data to determine if I should display a splash screen or the home screen. I am trying to use the ternary operator to see if the shared preferences contain a name or not (if yes then go to home screen else show splash screen). I am sharing my main file and my form code so please help me do this or suggest some other way as I am very new to this.

final val = _readName();
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  _saveEmpty();
  print(val);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'My Title',
      theme: ThemeData(
        textTheme: GoogleFonts.poppinsTextTheme(Theme.of(context).textTheme),
        primaryColor: kPrimaryColor,
        accentColor: kPrimaryColor,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: val != "a" ? HomeScreen() : SplashScreen(),
    );
  }
}

_readName() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  final value = prefs.getString("myName");
  print(value);
  return value;
}

_saveEmpty() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString("myName", "a");
}

Form:

TextFormField buildEmailFormField() {
    return TextFormField(
      keyboardType: TextInputType.emailAddress,
      onSaved: (newValue) {
        email = newValue;
        _saveEmail(newValue);
      },
      onChanged: (value) {
        if (value.isNotEmpty) {
          removeError(error: kEmailNullError);
        } else if (emailValidatorRegExp.hasMatch(value)) {
          removeError(error: kInvalidEmailError);
        }
        return null;
      },
      validator: (value) {
        if (value.isEmpty) {
          addError(error: kEmailNullError);
          return "";
        } else if (!emailValidatorRegExp.hasMatch(value)) {
          addError(error: kInvalidEmailError);
          return "";
        }
        return null;
      },
      decoration: InputDecoration(
        labelText: "Email",
        hintText: "Enter your email",
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Mail.svg"),
      ),
    );
  }

  TextFormField buildNameFormField() {
    return TextFormField(
      keyboardType: TextInputType.name,
      onSaved: (newValue) {
        name = newValue;
        _saveName(newValue);
      },
      onChanged: (value) {
        if (value.isNotEmpty) {
          removeError(error: kNameNullError);
        }
        return null;
      },
      validator: (value) {
        if (value.isEmpty) {
          addError(error: kNameNullError);
          return "";
        }
        return null;
      },
      decoration: InputDecoration(
        labelText: "Name",
        hintText: "Enter your name",
        floatingLabelBehavior: FloatingLabelBehavior.always,
      ),
    );
  }

  _saveName(val) async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'my_name';
    prefs.setString(key, val);
  }

  _saveEmail(val) async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'my_email';
    prefs.setString(key, val);
  }

I want to do with shared preferences because databases sound complicated to me so please help me. Thank You

Rijak Singh
  • 67
  • 1
  • 9
  • Does this answer your question? [How to use shared preferences to keep user logged in flutter?](https://stackoverflow.com/questions/54377188/how-to-use-shared-preferences-to-keep-user-logged-in-flutter) – swalog Nov 02 '20 at 14:04
  • What is going wrong with your approach? – shreyasm-dev Nov 03 '20 at 01:34

1 Answers1

0

My suggested way to implement this is to check the shared preference state while showing the splash screen and then navigate the user to the home screen or the login screen based on the result.

Here's how to do it,

  • Create separate screens for entering user data and home
  • Add the below splashscreen class as home in your main app
  • save the is_logged_in value as true when the user saves the entered data
  • check the is_logged_in value while showing the splash screen and navigate accordingly

SplashScreen
class SplashScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    startTimer();
  }

  @override
  Widget build(BuildContext context) {

    return Material(
      child: Center(child: AppIconWidget(image: Assets.appLogo)),
    );
  }

  startTimer() {
    var _duration = Duration(milliseconds: 2000);
    return Timer(_duration, navigate);
  }

  navigate() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();

    if (preferences.getBool(Preferences.is_logged_in) ?? false) {
      Navigator.of(context).pushNamed(Routes.home);
    } else {
      Navigator.of(context).pushNamed(Routes.login);
    }
  }
}

call it as home in your main class

home: SplashScreen()

Updated:
The preferences constant class which I have used should be like this, This value is used as the key to store the preference values we save

class Preferences {
  Preferences._();

  static const String is_logged_in = "isLoggedIn";
}
Kasun Thilina
  • 1,523
  • 2
  • 14
  • 20
  • Thanks for replying! in the get bool you have written Preferences with a capital P but it is not working for me. It is showing an error. Is it a typo or should I declare it somewhere? – Rijak Singh Nov 03 '20 at 06:52
  • You are welcome :), I have updated the answer. The Preferences class is a class created by me to store the key values for sharedpreferences. – Kasun Thilina Nov 03 '20 at 07:40
  • can you accept my answer as correct if you think my answer is correct and helpful ;) – Kasun Thilina Nov 03 '20 at 07:42
  • Thanks for replying i have marked it as correct. Thank you!! – Rijak Singh Nov 04 '20 at 08:05