本文介绍了每次抖动时如何更新 SharedPreferences 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一些保存在 SharedPreferences 中的值.我有一些带有提示文本和底部导航的文本字段.输入到文本字段中的文本将保存到共享首选项.我创建了名为 loadUserData(); 的类.使用 SharedPreferences 在本地保存数据.

I am trying to get some values saved in the SharedPreferences . I have a few textfields with hint text and bottom navigation. Text entered into the textfield will be saved to shared preferences. I created class named loadUserData(); to save data locally using SharedPreferences .

 void initState() {
    super.initState();
    isButtonDisabled = false;
    loadUserData();
    myFocusNode = FocusNode();
    telephoneNode = FocusNode();
    adresseNode = FocusNode();
    emailNode = FocusNode();
    passwordNode = FocusNode();
   // future = boxApi.getUser();
    // future = loadUserData();
  }

loadUserData() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var user = jsonDecode(localStorage.getString('user'));

    if (user != null) {
      setState(() {
        name = user['name'];
        phone = user['phone'];
        adress = user['adress'];
        email = user['email'];
      });
    }
  }

在那之后,我尝试从 SharedPreferences 获取数据并将其显示在屏幕上:

After that , I tried to fetch data from SharedPreferences and display it on screen like that :

如您所见,用户可以修改他的姓名、地址...我的问题是当用户修改某些数据时 ==>直到他下次登录时才更新数据.我希望用户可以同时修改和更新新值(不需要离开页面).

as you see the user can modify his name , adress... My problem is when the user modify some data ==> the data not updated until he login next time . I want the user can modify and update the new value at the same time ( don't need leave page) .

这是我的代码;

Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SafeArea(
        /* minimum: const EdgeInsets.only(
            top: 20.0, right: 5.0, left: 5.0, bottom: 10.0),*/
        child: Center(
      child: Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: Color(0xFFF6F7F8),
          body: SingleChildScrollView(
              child: Form(
                  key: _formKey,
                  child: FutureBuilder(
                      future: future,
                      //   boxApi.getUser(),
                      //print(adress);
                      builder: (context, snapshot) {
                        // ignore: missing_return
                        // print(snapshot.data);
                        switch (snapshot.connectionState) {
                          case ConnectionState.none:
                            return Text('no connection');
                          case ConnectionState.active:
                          case ConnectionState.waiting:
                            return Center(
                              child: CircularProgressIndicator(),
                            );
                            break;
                          case ConnectionState.done:
                            if (snapshot.hasError) {
                              return Text('error');
                            } else if (snapshot.hasData) {
                              // String price = snapshot.data['body'].;
                              //  print("${snapshot.data}");
                              return Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  Container(
                                    padding: EdgeInsets.only(top: 16),
                                    width: MediaQuery.of(context).size.width,
                                    height:
                                        MediaQuery.of(context).size.height / 4,
                                    decoration: BoxDecoration(
                                        boxShadow: [
                                          BoxShadow(
                                              color: Colors.white60,
                                              blurRadius: 15.0,
                                              offset: Offset(0.0, 0.75))
                                        ],
                                        gradient: LinearGradient(
                                          begin: Alignment(0.5, 0.85),
                                          end: Alignment(0.48, -1.08),
                                          colors: [
                                            const Color(0xFF0B0C3A),
                                            const Color(0xFF010611),
                                          ],
                                          stops: [
                                            0.0,
                                            0.5,
                                          ],
                                        ),
                                        //color: blue,
                                        borderRadius: BorderRadius.only(
                                            bottomRight: Radius.circular(32),
                                            bottomLeft: Radius.circular(32))),
                                    child: Column(
                                      children: [
                                        Row(
                                          children: [
                                            SizedBox(
                                              width: 30,
                                            ),
                                            Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    "$name",
                                                    style: TextStyle(
                                                        color: Colors.white,
                                                        fontSize: 25,
                                                        fontWeight:
                                                            FontWeight.bold),
                                                  ),
                                                  SizedBox(
                                                    height: 10,
                                                  ),
                                                  Text(
                                                    "$phone",
                                                    style: TextStyle(
                                                      color: Colors.white60,
                                                      fontSize: 18,
                                                      //fontWeight: FontWeight.w300
                                                    ),
                                                  ),
                                                ])
                                          ],
                                        ),
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.end,
                                          children: [
                                            Container(
                                                margin: EdgeInsets.symmetric(
                                                    vertical: 10),
                                                width: size.width * 0.4,
                                                child: ElevatedButton(
                                                  onPressed: () {
                                                    if (_nameController.text ==
                                                            "" &&
                                                        _emailController.text ==
                                                            "" &&
                                                        _adressController
                                                                .text ==
                                                            "") {
                                                      setState(() =>
                                                          isButtonDisabled =
                                                              true);
                                                    } else {
                                                      editUserProfile();
                                                    }
                                                  },
                                                  // editUserProfile();

                                                  child: Text('Enregistrer'),
                                                  style:
                                                      ElevatedButton.styleFrom(
                                                    primary: Colors.transparent,
                                                    shape:
                                                        RoundedRectangleBorder(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        20),
                                                            side: BorderSide(
                                                                color: Colors
                                                                    .white)),
                                                  ),
                                                )),
                                            SizedBox(
                                              width: 20,
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  ),
                                  Container(
                                    height: MediaQuery.of(context).size.height /
                                        1.5,
                                    // padding: EdgeInsets.only(
                                    //   top: 32,
                                    // ),
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          children: [
                                            Container(
                                              width: size.width * 0.94,
                                              child: Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                children: [
                                                  Container(
                                                    padding: EdgeInsets.only(
                                                        left: 10,
                                                        right: 10,
                                                        bottom: 20,
                                                        top: 20),
                                                    child: Column(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .start,
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        Row(
                                                          mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .spaceBetween,
                                                          children: [
                                                            Text(
                                                              'Votre nom :',
                                                              style: TextStyle(
                                                                  color: Color(
                                                                      0xFF4053FCF),
                                                                  fontSize: 16,
                                                                  fontWeight:
                                                                      FontWeight
                                                                          .w600),
                                                            ),
                                                            IconButton(
                                                                icon: Icon(
                                                                  CommunityMaterialIcons
                                                                      .pencil,
                                                                  color: Colors
                                                                      .grey,
                                                                ),
                                                                onPressed: () {
                                                                  myFocusNode
                                                                      .requestFocus();
                                                                  setState(() {
                                                                    enableup =
                                                                        true;
                                                                  });
                                                                })
                                                          ],
                                                        ),
                                                        TextFormField(
                                                          controller:
                                                              _nameController,
                                                          enabled: enableup,
                                                          focusNode:
                                                              myFocusNode,
                                                          enableInteractiveSelection:
                                                              false,
                                                          keyboardType:
                                                              TextInputType
                                                                  .text,
                                                          decoration: InputDecoration(
                                                              hintText: "$name",
                                                              hintStyle: TextStyle(
                                                                  color: Colors
                                                                      .grey,
                                                                  fontSize:
                                                                      14.0)),
                                                        ),

推荐答案

我认为您需要重新加载 Sharedpreference 值.

I think you need to reload the Sharedpreference value.

SharedPreferences localStorage = await SharedPreferences.getInstance();
await localStorage.reload();

这篇关于每次抖动时如何更新 SharedPreferences 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:00