【问题标题】:How to store user data in flutter app with shared preferences如何将用户数据存储在具有共享偏好的 Flutter 应用程序中
【发布时间】: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


【解决方案1】:

我建议的实现方式是在显示初始屏幕时检查共享首选项状态,然后根据结果将用户导航到主屏幕或登录屏幕。

这是怎么做的,

  • 为输入用户数据和主页创建单独的屏幕
  • 在您的主应用中添加以下启动画面类作为主页
  • 当用户保存输入的数据时,将 is_logged_in 的值保存为 true
  • 在显示初始屏幕时检查 is_logged_in 值并进行相应导航

闪屏
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);
    }
  }
}

在你的主课中称它为家

home: SplashScreen()

更新:
我使用的首选项常量类应该是这样的, 这个值作为key来存储我们保存的偏好值

class Preferences {
  Preferences._();

  static const String is_logged_in = "isLoggedIn";
}

【讨论】:

  • 感谢您的回复!在 get bool 中,您已经用大写 P 编写了 Preferences,但它对我不起作用。它显示一个错误。是错字还是我应该在某处声明?
  • 不客气 :),我已经更新了答案。 Preferences 类是我创建的一个类,用于存储 sharedpreferences 的键值。
  • 如果您认为我的回答正确且有帮助,您能接受我的回答吗?)
  • 感谢您的回复,我已将其标记为正确。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 2021-10-11
相关资源
最近更新 更多