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