【发布时间】:2021-02-14 18:54:27
【问题描述】:
我想在我的 Flutter 应用程序中存储基本用户数据(姓名和电子邮件)(使用共享首选项),并且我想使用这些数据来确定我应该显示启动屏幕还是主屏幕。我正在尝试使用三元运算符来查看共享首选项是否包含名称(如果是,则转到主屏幕,否则显示启动画面)。我正在共享我的主文件和表单代码,所以请帮我这样做或建议其他方式,因为我对此很陌生。
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");
}
表格:
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);
}
我想处理共享首选项,因为数据库对我来说听起来很复杂,所以请帮助我。谢谢你
【问题讨论】:
-
你的方法出了什么问题?
标签: flutter validation