Flutter - How to ensure the switch is on even after clicking on the back button?

自闭症网瘾萝莉.ら 提交于 2021-02-10 06:33:14

问题


I have a settings menu with 8 listTiles and If I turn on one of the switches, the issue is - when I click on the back button and click on the settings menu again, the switch is turned off ... what would I have to add to make sure the switch is on even if the back button is clicked?

After this- what ever switch is turned on that's the color image I want to display in another class ..... that is why I need to ensure only one switch is on at one time, and that once the user clicks the back button and clicks back into the setting page the switch is still turned on ... How can I go about doing these two things?

import 'dart:ui';
import 'package:Quran_highlighter/Widgets/styling.dart';
import 'package:adobe_xd/adobe_xd.dart';
import 'dart:io';
import 'package:Quran_highlighter/main.dart';
import 'package:flutter/rendering.dart';
import 'package:system_shortcuts/system_shortcuts.dart';
import 'package:Quran_highlighter/Widgets/NavDrawer.dart';
import 'package:flutter/material.dart';
import 'package:zoom_widget/zoom_widget.dart';
import 'package:flutter/gestures.dart';
import 'package:Quran_highlighter/Widgets/size_config.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'package:peek_and_pop/misc.dart' as PeekAndPopMisc;
import 'package:provider/provider.dart';

class SettingsMenu extends StatefulWidget {
  @override
  _SettingsMenuState createState() => _SettingsMenuState();
}

// body: ListView.builder(
// itemCount: 15,
// itemBuilder: (BuildContext context, int index) {
// if (index == 0) {
// return SizedBox(height: 15.0);
// } else if (index == 5) {
// return SizedBox(height: 100.0);
// }
// return Container(
// alignment: Alignment.center,
class _SettingsMenuState extends State<SettingsMenu> with ChangeNotifier {
  // int _inc = 0;
  bool _enabled;
  bool _icymistEnable = true;
  bool _heartEnable = true;
  bool _deepoceanEnable = true;
  bool _flowerEnable = true;
  bool _gardenEnable = true;
  bool _paradiseEnable = true;
  bool _midnightparadisEnable = true;
  bool _midnightEnable = true;
  bool _icymistSwitch = false;
  bool _icymistColor = false;
  bool _heartColor = false;
  bool _heartSwitch = false;
  bool _deepoceanSwitch = false;
  bool _deepoceanColor = false;
  bool _flowerColor = false;
  bool _flowerSwitch = false;
  bool _gardenSwitch = false;
  bool _gardenColor = false;
  bool _paradiseColor = false;
  bool _paradiseSwitch = false;
  bool _midnightparadiseSwitch = false;
  bool _midnightparadiseColor = false;
  bool _midnightColor = false;
  bool _midnightSwitch = false;
  String image1 = "test/assets/Para 1 - Alif-laam-meem no color/quranpg2-1.png";
  bool _showPreview = false;
  String _image =
      "test/assets/Para 1 - Color - Alif Laam Meem/pg2_bonus_cool_ice10x___2.png";
  // changeValue(bool value) {
  //   setState(() {
  //     _inc++;
  //     _value = value;
  //   });
  // }

  onpress() {
    GestureDetector(
        onLongPress: () {
          print("longpress");
        },
        onLongPressUp: () {
          print("longpressup");
        },
        child: Card());
  }

  changetoIcyMistImage() {
    // setState(() {
    return GestureDetector(onLongPress: () {
      setState(() {
        _showPreview = true;
        _image =
            "test/assets/Para 1 - Color - Alif Laam Meem/pg2_bonus_cool_ice10x___2.png";
      });
    });
  }
  // );

  trythis() {
    setState(() {
      RepaintBoundary(
          key: PeekAndPopMisc.background,
          child: MaterialApp(
              title: 'Peek & Pop Demo',
              home: MyHomePage(title: 'Peek & Pop Demo')));
    });
  }

  activateIcyMistHighlighter() {
    setState(() {
      _icymistColor = true;
      _icymistSwitch = true;
      _icymistEnable = true;
      _heartColor = false;
      _heartSwitch = false;
      // _heartEnable = !_heartEnable;
      _heartEnable = true;
      _deepoceanColor = false;
      _deepoceanSwitch = false;
      _deepoceanEnable = true;
      // _deepoceanEnable = !_deepoceanEnable;
      _flowerColor = false;
      _flowerSwitch = false;
      _flowerEnable = true;
      // _flowerEnable = !_flowerEnable;
      _gardenColor = false;
      _gardenSwitch = false;
      _gardenEnable = true;
      // _gardenEnable = !_gardenEnable;
      _paradiseColor = false;
      _paradiseSwitch = false;
      _paradiseEnable = true;
      // _paradiseEnable = !_paradiseEnable;
      _midnightparadiseColor = false;
      _midnightparadiseSwitch = false;
      _midnightparadisEnable = true;
      // _midnightparadisEnable = !_midnightparadisEnable;
      _midnightColor = false;
      _midnightEnable = true;
      // _midnightEnable = !_midnightEnable;
      _midnightSwitch = false;
      // notifyListeners();
    });
  }

  activateHeartHighlighter(bool value) {
    setState(() {
      _heartColor = true;
      _heartSwitch = true;
      _heartEnable = true;
      _icymistColor = false;
      _icymistSwitch = false;
      _icymistEnable = true;
      _deepoceanColor = false;
      _deepoceanSwitch = false;
      _deepoceanEnable = true;
      _flowerColor = false;
      _flowerSwitch = false;
      _flowerEnable = true;
      _gardenColor = false;
      _gardenSwitch = false;
      _gardenEnable = true;
      _paradiseColor = false;
      _paradiseSwitch = false;
      _paradiseEnable = true;
      _midnightparadiseColor = false;
      _midnightparadiseSwitch = false;
      _midnightparadisEnable = true;
      _midnightColor = false;
      _midnightEnable = true;
      _midnightSwitch = false;
      notifyListeners();
      // if (activateIcyMistHighlighter(value)) {
      //   setState(() {
      //     // _heartColor = false;
      //   });
    }
        // }
        );
  }
  // }

  activateDeepOceanHighlighter(bool value) {
    setState(() {
      _deepoceanColor = true;
      _deepoceanSwitch = true;
      _deepoceanEnable = true;
      _heartColor = false;
      _heartSwitch = false;
      _heartEnable = true;
      _icymistColor = false;
      _icymistSwitch = false;
      _icymistEnable = true;
      _flowerColor = false;
      _flowerSwitch = false;
      _flowerEnable = true;
      _gardenColor = false;
      _gardenSwitch = false;
      _gardenEnable = true;
      _paradiseColor = false;
      _paradiseSwitch = false;
      _paradiseEnable = true;
      _midnightparadiseColor = false;
      _midnightparadiseSwitch = false;
      _midnightparadisEnable = true;
      _midnightColor = false;
      _midnightEnable = true;
      _midnightSwitch = false;
    });
  }

  activateFlowerHighlighter(bool value) {
    setState(() {
      _flowerColor = true;
      _flowerSwitch = true;
      _flowerEnable = true;
      _heartColor = false;
      _heartSwitch = false;
      _heartEnable = true;
      _icymistColor = false;
      _icymistSwitch = false;
      _icymistEnable = true;
      _deepoceanColor = false;
      _deepoceanSwitch = false;
      _deepoceanEnable = true;
      _gardenColor = false;
      _gardenSwitch = false;
      _gardenEnable = true;
      _paradiseColor = false;
      _paradiseSwitch = false;
      _paradiseEnable = true;
      _midnightparadiseColor = false;
      _midnightparadiseSwitch = false;
      _midnightparadisEnable = true;
      _midnightColor = false;
      _midnightEnable = true;
      _midnightSwitch = false;
    });
  }

  activateGardenHighlighter(bool value) {
    setState(() {
      _gardenColor = true;
      _gardenSwitch = true;
      _gardenEnable = true;
      _flowerColor = false;
      _flowerSwitch = false;
      _flowerEnable = true;
      _heartColor = false;
      _heartSwitch = false;
      _heartEnable = true;
      _icymistColor = false;
      _icymistSwitch = false;
      _icymistEnable = true;
      _deepoceanColor = false;
      _deepoceanSwitch = false;
      _deepoceanEnable = true;
      _paradiseColor = false;
      _paradiseSwitch = false;
      _paradiseEnable = true;
      _midnightparadiseColor = false;
      _midnightparadiseSwitch = false;
      _midnightparadisEnable = true;
      _midnightColor = false;
      _midnightEnable = true;
      _midnightSwitch = false;
    });
  }

  activateParadiseHighlighter(bool value) {
    setState(() {
      _paradiseColor = true;
      _paradiseSwitch = true;
      _paradiseEnable = true;
      _flowerColor = false;
      _flowerSwitch = false;
      _flowerEnable = true;
      _heartColor = false;
      _heartSwitch = false;
      _heartEnable = true;
      _icymistColor = false;
      _icymistSwitch = false;
      _icymistEnable = true;
      _deepoceanColor = false;
      _deepoceanSwitch = false;
      _deepoceanEnable = true;
      _gardenColor = false;
      _gardenSwitch = false;
      _gardenEnable = true;
      _midnightparadiseColor = false;
      _midnightparadiseSwitch = false;
      _midnightparadisEnable = true;
      _midnightColor = false;
      _midnightEnable = true;
      _midnightSwitch = false;
    });
  }

  activateMidnightParadiseHighlighter(bool value) {
    setState(() {
      _midnightparadiseColor = true;
      _midnightparadiseSwitch = true;
      _midnightparadisEnable = true;
      _paradiseColor = false;
      _paradiseSwitch = false;
      _paradiseEnable = true;
      _flowerColor = false;
      _flowerSwitch = false;
      _flowerEnable = true;
      _heartColor = false;
      _heartSwitch = false;
      _heartEnable = true;
      _icymistColor = false;
      _icymistSwitch = false;
      _icymistEnable = true;
      _deepoceanColor = false;
      _deepoceanSwitch = false;
      _deepoceanEnable = true;
      _gardenColor = false;
      _gardenSwitch = false;
      _gardenEnable = true;
      _midnightColor = false;
      _midnightEnable = true;
      _midnightSwitch = false;
    });
  }

  activateMidnightHighlighter(bool value) {
    setState(() {
      _midnightColor = true;
      _midnightSwitch = true;
      _midnightEnable = true;
      _midnightparadiseColor = false;
      _midnightparadiseSwitch = false;
      _midnightparadisEnable = true;
      _paradiseColor = false;
      _paradiseSwitch = false;
      _paradiseEnable = true;
      _flowerColor = false;
      _flowerSwitch = false;
      _flowerEnable = true;
      _gardenColor = false;
      _gardenSwitch = false;
      _gardenEnable = true;
      _heartColor = false;
      _heartSwitch = false;
      _heartEnable = true;
      _icymistColor = false;
      _icymistSwitch = false;
      _icymistEnable = true;
      _deepoceanColor = false;
      _deepoceanSwitch = false;
      _deepoceanEnable = true;
    });
  }

  getColor(bool enabled) {
    if (_enabled == true) {
      return Colors.blue;
    } else {
      return Colors.purple;
    }
  }

  @override
  Widget build(BuildContext context) {
    ///
    return Scaffold(
        backgroundColor: Colors.white,
        // Color(0xFFFAFAFA),
        appBar: AppBar(
            backgroundColor: Colors.cyan,
            title: Text("Settings Menu",
                style: TextStyle(color: styling.appBarTextcolor)),
            leading: FlatButton(
                textColor: Colors.white,
                child: Icon(styling.appBarBackArrowIcon),
                onPressed: () {
                  Navigator.pop(context, false);
                  // WillPopScope(
                  //   onWillPop: () async {
                  //     // You can await in the calling widget for my_value and handle when complete.
                  //     Navigator.pop(context, 'my_value');
                  //     return false;
                  // },
                  // );

                  // Navigator.push(
                  //     context,
                  //     MaterialPageRoute(
                  //       builder: (context) => NavDrawer(),
                  //     ));
                }),
            actions: <Widget>[
              FlatButton(
                textColor: Colors.white,
                child: Text(
                  'Help',
                  style: TextStyle(
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                onPressed: () => print('Help'),
              )
            ]),
        body: new SingleChildScrollView(
            child: Container(
                constraints: BoxConstraints.expand(
                  // BoxConstraints
                  // BoxConstraints.expand(
                  height: 1200,

                  // .expand(
                  // width: SizeConfig.screenWidth / 0.5,
                  // height: SizeConfig.screenHeight / 0.5,
                ),

                // children: [
                child: Column(
                    // mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      // const SizedBox(
                      //   height: 5.0,
                      //   width: 10.0,
                      // ),

                      Text(
                        "English Highlighter Selection:",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          backgroundColor: Colors.cyan,
                          fontSize: 20.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Divider(
                        color: Colors.black,
                      ),
                      // );
                      // }
// }
                      ListTile(
                          leading: Icon(
                            Icons.highlight,
                            color: Colors.cyan,
                          ),
                          tileColor:
                              _icymistColor ? Colors.cyan : Colors.transparent,
                          title: Text("Icy Mist"),
                          enabled: _icymistEnable,
                          subtitle: Text(
                              "A nice cooling Triple Gradient light blue highlighter with Teal and a hint of white"),
                          trailing: Icon(Icons.view_compact),

                          // onLongPress: changetoIcyMistImage()
//  return GestureDetector(
//               onLongPress: () {
//                 setState(() {
//                   _showPreview = true;
//                   _image = "assets/images/${images[index]}";
//                 });
//               },
//               onLongPressEnd: (details) {
//                 setState(() {
//                   _showPreview = false;
//                 });
//               },
//               child: Padding(
//                 padding: const EdgeInsets.all(4.0),
//                 child: Card(
//                   elevation: 4,
//                   shape: RoundedRectangleBorder(
//                     borderRadius: BorderRadius.circular(5.0),
//                   ),
//                   clipBehavior: Clip.hardEdge,
//                   child: Image.asset("assets/images/${images[index]}"),
//                 ),
//               ),
//             );
//           },
//         ),
//         if (_showPreview) ...[
//           BackdropFilter(
//             filter: ImageFilter.blur(
//               sigmaX: 5.0,
//               sigmaY: 5.0,
//             ),
//             child: Container(
//               color: Colors.white.withOpacity(0.6),
//             ),
//           ),
//           Container(
//             child: Center(
//               child: ClipRRect(
//                 borderRadius: BorderRadius.circular(10.0),
//                 child: Image.asset(
//                   _image,
//                   height: 300,
//                   width: 300,
//                 ),

                          onTap: () {
                            onpress();
                          }
                          //   setState(() {
                          //     _showPreview = true;
                          //     _image =
                          //         "test/assets/Para 1 - Color - Alif Laam Meem/pg2_bonus_cool_ice10x___2.png";
                          //   });
                          // },

                          // onLongPressEnd: (details) {
                          //   setState(() {
                          //     _showPreview = false;
                          //   });
                          // },
                          // onTap: () {
                          //   // print("hey what is up");
                          //   changetoIcyMistImage();
                          // setState(() {
                          //   _color = !_color;
                          // });
                          // },
                          // ),
                          // }
                          ),
                      // ),
                      Switch(
                        // contentPadding: const EdgeInsets.all(0),
                        value: _icymistSwitch,
                        activeColor: Colors.cyan,
                        // title: Text("final one"),
                        onChanged: (bool value) => activateIcyMistHighlighter(),

                        // Center(
                        //   child: new Text("value ${_inc}"),
                        // ),

                        // ),
                      ),
                      Divider(
                        color: Colors.black,
                      ),
                      ListTile(
                        leading: Icon(
                          Icons.highlight,
                          color: Colors.red,
                        ),
                        enabled: _heartEnable,
                        tileColor:
                            _heartColor ? Colors.red : Colors.transparent,
                        title: Text("Heart"),
                        subtitle: Text(
                            "A Strong Hearty Double Gradient highlighter with a hint of black at the top"),
                        trailing: Icon(Icons.view_compact),
                        onTap: () {},
                      ),
                      Switch(
                          // contentPadding: const EdgeInsets.all(0),
                          value: _heartSwitch,
                          activeColor: Colors.red,
                          // title: Text("final one"),
                          onChanged: (bool _heartColor) =>
                              activateHeartHighlighter(_heartColor)),
                      // ),
                      Divider(
                        color: Colors.black,
                      ),
                      ListTile(
                        leading: Icon(
                          Icons.highlight,
                          color: Colors.blue,
                        ),
                        tileColor:
                            _deepoceanColor ? Colors.blue : Colors.transparent,
                        enabled: _deepoceanEnable,
                        // tileColor: Colors.transparent,
                        // getColor(!_enabled),
                        title: Text("Deep Ocean"),
                        subtitle: Text(
                            "Deep beneath the ocean comes this equisite Double Gradient highlighter with a hint of black"),
                        trailing: Icon(Icons.view_compact),
                        onTap: () {},
                      ),
                      Switch(
                          // contentPadding: const EdgeInsets.all(0),
                          value: _deepoceanSwitch,
                          activeColor: Colors.blue,
                          // title: Text("final one"),
                          onChanged: (bool _deepoceanColor) =>
                              activateDeepOceanHighlighter(_deepoceanColor)),
                      // ),
                      Divider(
                        color: Colors.black,
                      ),
                      ListTile(
                        leading: Icon(
                          Icons.highlight,
                          color: Colors.pink,
                        ),
                        enabled: _flowerEnable,
                        tileColor:
                            _flowerColor ? Colors.pink : Colors.transparent,
                        title: Text("Flower"),
                        subtitle: Text(
                            "A bright Fuschia Flower highlighter that has a perfect shade of dark and light"),
                        trailing: Icon(Icons.view_compact),
                        onTap: () {},
                      ),
                      Switch(
                          // contentPadding: const EdgeInsets.all(0),
                          value: _flowerSwitch,
                          activeColor: Colors.pink,
                          // title: Text("final one"),
                          onChanged: (bool _flowerColor) =>
                              activateFlowerHighlighter(_flowerColor)),
                      // ),
                      Divider(
                        color: Colors.black,
                      ),
                      ListTile(
                        leading: Icon(
                          Icons.highlight,
                          color: Colors.green,
                        ),
                        enabled: _gardenEnable,
                        tileColor:
                            _gardenColor ? Colors.green : Colors.transparent,
                        title: Text("Garden"),
                        subtitle: Text(
                            "A Foresty Green highlighter with a Double Gradient shade of light and dark"),
                        trailing: Icon(Icons.view_compact),
                        onTap: () {},
                      ),
                      Switch(
                          // contentPadding: const EdgeInsets.all(0),
                          value: _gardenSwitch,
                          activeColor: Colors.green,
                          // title: Text("final one"),
                          onChanged: (bool _gardenColor) =>
                              activateGardenHighlighter(_gardenColor)),
                      // ),
                      Divider(
                        color: Colors.black,
                      ),
                      ListTile(
                        leading: Icon(
                          Icons.highlight,
                          color: Colors.teal,
                        ),
                        enabled: _paradiseEnable,
                        tileColor:
                            _paradiseColor ? Colors.teal : Colors.transparent,
                        title: Text("Paradise"),
                        subtitle: Text(
                            "A Nice cool Double Gradient Teal and skyBlue highligher which has ligh and dark shades"),
                        trailing: Icon(Icons.view_compact),
                        onTap: () {},
                      ),
                      Switch(
                          // contentPadding: const EdgeInsets.all(0),
                          value: _paradiseSwitch,
                          activeColor: Colors.teal,
                          // title: Text("final one"),
                          onChanged: (bool _paradiseColor) =>
                              activateParadiseHighlighter(_paradiseColor)),
                      // ),
                      Divider(
                        color: Colors.black,
                      ),
                      ListTile(
                        leading: Icon(Icons.highlight,
                            color: Colors.purpleAccent[700]),
                        enabled: _midnightparadisEnable,
                        tileColor: _midnightparadiseColor
                            ? Colors.tealAccent
                            : Colors.transparent,
                        title: Text("Midnight Paradise"),
                        subtitle: Text(
                            "Most Exquisite to the eyes top with a nice Purple Midnight shade and the bottom with a Light Paradise light teal highlight"),
                        trailing: Icon(Icons.view_compact),
                        onTap: () {},
                      ),
                      Switch(
                          // contentPadding: const EdgeInsets.all(0),
                          value: _midnightparadiseSwitch,
                          activeColor: Colors.tealAccent,
                          // title: Text("final one"),
                          onChanged: (bool _midnightparadiseColor) =>
                              activateMidnightParadiseHighlighter(
                                  _midnightparadiseColor)),
                      // ),
                      Divider(
                        color: Colors.black,
                      ),
                      ListTile(
                        leading: Icon(
                          Icons.highlight,
                          color: Colors.purple,
                        ),
                        enabled: _midnightEnable,
                        tileColor:
                            _midnightColor ? Colors.purple : Colors.transparent,
                        title: Text("Midnight"),
                        subtitle: Text(
                            "The night so dim the Midnight shade of purple mixed with a dark night highlighter"),
                        // tileColor: Colors.,
                        trailing: Icon(Icons.view_compact),
                        onTap: () {},
                      ),
                      Switch(
                          // contentPadding: const EdgeInsets.all(0),
                          value: _midnightSwitch,
                          activeColor: Colors.purple,
                          // title: Text("final one"),
                          onChanged: (bool _midnightColor) =>
                              activateMidnightHighlighter(_midnightColor)),
                      // ),
                      Divider(
                        color: Colors.black,
                      ),
                    ]))));
  }
}

回答1:


try to define global variables if u want that in entire app but it will get lost once the user close the app.

the best way is to store that bool value in database like shared_preferences or 'hive` . Here is the doc of https://pub.dev/packages/shared_preferences and https://pub.dev/packages/hive resp

SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('switch', true);

for getting bool value

bool counter = prefs.getBool('switch') ?? false;



回答2:


If you want to store the values only for one session, you could use static members of a class, like this:

class Values{
  static List<bool> checkBoxValues = [false, false...];
}

If you want to save settings, you will have to use shared_preferences:

SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('switch', true);

To get a value from anywhere in the program, use prefs.getBool('switch')




回答3:


I'd prefer sending it back as bool data using the Navigator like:

Navigator.pop(context, true);

for more info, have a look at the docs



来源:https://stackoverflow.com/questions/64548263/flutter-how-to-ensure-the-switch-is-on-even-after-clicking-on-the-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!