Сохранить состояние переключателя в Flutter с sharedPreferences - PullRequest
0 голосов
/ 03 мая 2020

Как я могу сохранить состояние switch для будущего ?, прямо сейчас, когда я нажимаю на switch на true и возвращаюсь на предыдущую страницу, мой switch меняется на false, но я хочу сохранить это статус для другого действия пользователя в будущем,

Я прочитал, что могу использовать AutomaticKeepAliveClientMixin, но это не работает для меня, поэтому я считаю, что sharedPreferences будет лучшим выбором, но я не знаю, как это сделать

мой код:

class LocationScreenState extends State<LocationScreen> with AutomaticKeepAliveClientMixin{
  @override bool get wantKeepAlive => true;
  bool state = false;
  // PermissionStatus _status;
  PermissionStatus _status;


  @override
  Widget build(BuildContext context){
    // super.build(context);
    return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            backgroundColor: Colors.white,
            iconTheme: IconThemeData(color: Colors.black),
            title: Text(AppTranslations.of(context).text("settings_location"), style: TextStyle(color: Colors.black, letterSpacing: 1)),
            elevation: 0.0,
            centerTitle: true,
            bottom: PreferredSize(child: Container(color: Colors.black, height: 0.1), preferredSize: Size.fromHeight(0.1),),
          ),
          body: Container(
            child: Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(top: 40.0),
                    child: SizedBox(
                      height: 150,
                      width: 800,
                    child: Card(
                      elevation: 5.0,
                      child: Padding(
                        padding: EdgeInsets.all(15.0),
                        child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          const ListTile(
                            title: Text('xxx'),
                            subtitle: Text('xxx'),
                          ),
                          Row(
                            children: <Widget>[
                              Switch(
                                value: state,
                                onChanged: (bool s) {
                                  setState(() {
                                    state = s;
                                    if(state){
                                      // _askPermission();
                                    }
                                  });
                                },
                              )
                            ],
                          )
                        ],
                      ),
                      )
                    )
                  ),
                  )
                ],
              )
            ],
          )
    );
  }
}

спасибо за любую помощь

///////////////// //////////////////////////////////////////

1 Ответ

1 голос
/ 03 мая 2020

Попробуйте,

  @override
  void initState(){
    super.initState();
    getSwitchStatus();
  }

  Future<bool> getSwitchStatus() async {
    sharedPreferences = await SharedPreferences.getInstance();
    bool status = sharedPreferences.getBool("switchStatus");
    return status;
  }

в вашем методе сборки:

Row(
 children: <Widget>[
     FutureBuilder(
         future: SharedPreferences.getInstance(),
         builder: (context, snapshot){
            return Switch(
             value: sharedPreferences.getBool("switchStatus"),
             onChanged: (bool s) {
               switchState = s;
                 sharedPreferences.setBool("switchStatus", switchState);
                 setState((){
                     if(switchState){
                       requestLocationPermission();
                        }
                       });
                      },
                     );
                    }
                   ),

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...