首页 > 解决方案 > 如何保持页面状态在颤动?

问题描述

我在 a 中有一个项目列表DragSelectGridView,所以我想保留我选择的项目的状态。

假设我的应用程序中有 5 个页面,我使用pushReplacement从第 1 页导航到第 2 页。第 2 页是我从中选择项目的位置,DragSelectGridView然后我使用pushReplacement第 3 页和从第 3 页导航到第 4 页。当我使用pushReplacement返回页面导航时2 我选择的所有项目都已处置。

即使我关闭应用程序,我也想保持我在第 2 页中选择的项目的状态。

我已经尝试使用SharePrefrences但我没有得到它..

这是我的代码:

class _IntresetState extends State<Intereset> {
  final controller = DragSelectGridViewController();
  final scrollcontrol = ScrollController();

  @override
  void initState() {
    super.initState();
    controller.addListener(scheduleRebuild);
  }

  @override
  void dispose() {
    controller.removeListener(scheduleRebuild);
    super.dispose();
  }

  void scheduleRebuild() => setState(() {});

  List<InterestModel> interestIn = [
    InterestModel('assets/Art & Design.jpeg', 'Art & Design'),
    InterestModel('assets/Tech.jpeg', 'Tech'),
    InterestModel('assets/Food.jpeg', 'Food'),
    InterestModel('assets/Animal.jpeg', 'Animal'),
    InterestModel('assets/Fitness & Health.jpeg', 'Fitness & Health'),
    InterestModel('assets/Car.jpeg', 'Car'),
    InterestModel('assets/Sport.jpeg', 'Sport'),
    InterestModel('assets/Book.jpeg', 'Book'),
    InterestModel('assets/Game.jpeg', 'Game'),
    InterestModel('assets/Film.jpeg', 'Film'),
    InterestModel('assets/Travelling.jpeg', 'Travelling'),
    InterestModel('assets/Tv & Music.jpeg', 'Tv & Music'),
    InterestModel('assets/Dancing.jpeg', 'Dancing'),
    InterestModel('assets/Cooking.jpeg', 'Cooking'),
    InterestModel('assets/Learning.jpeg', 'Learning'),
    InterestModel('assets/Pet.jpeg', 'Pet'),
    InterestModel('assets/Politics.jpeg', 'Politics'),
    InterestModel('assets/Photography.jpeg', 'Photography')
  ];
  @override
  Widget build(BuildContext context) {
    return ProgressHUD(
      child: Builder(
        builder: (context) => Scaffold(
          backgroundColor: Theme.of(context).backgroundColor,
          appBar: AppBar(
            elevation: 0,
            backgroundColor: Colors.transparent,
            leading: Container(),
            actions: [
              GestureDetector(
                onTap: () async {
                  final progress = ProgressHUD.of(context);
                  progress?.show();
                  final getLength = controller.value.selectedIndexes
                      .map((e) => interestIn[e].name)
                      .toList();
                  if (getLength.length <= 0) {
                    print(getLength.length);
                    progress?.dismiss();
                    await Flushbar(
                      title: 'Ops!',
                      message: 'Select one Interest !!!',
                      duration: Duration(seconds: 3),
                    ).show(context);
                  } else {
                    SharedPreferences pref =
                        await SharedPreferences.getInstance();
                    await pref.setBool('interest', true);
                    await firestore
                        .collection('interest')
                        .doc(auth.currentUser?.uid)
                        .set({'Interest': getLength}).then(
                      (value) => Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(
                          builder: (_) => Done(),
                        ),
                      ),
                    );
                    progress?.dismiss();
                  }
                },
                child: Container(
                  height: 40,
                  width: 40,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    gradient: LinearGradient(
                      colors: [
                        Constants.color1,
                        Constants.color2,
                      ],
                    ),
                  ),
                  child: Center(
                      child: Icon(
                    Icons.check_outlined,
                    size: 18,
                    color: Colors.white,
                  )),
                ),
              ),
              SizedBox(
                width: 20,
              ),
            ],
          ),
          extendBodyBehindAppBar: true,
          body: SafeArea(
            minimum: EdgeInsets.all(10.0),
            child: Container(
              height: double.infinity,
              width: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(bottom: 10.0),
                    child: Text('Select Interests',
                        style: GoogleFonts.raleway(
                          textStyle: TextStyle(
                            color: Theme.of(context).primaryColor,
                            fontSize: 30,
                            fontWeight: FontWeight.bold,
                          ),
                        )),
                  ),
                  Expanded(
                    child: DragSelectGridView(
                        shrinkWrap: false,
                        scrollController: scrollcontrol,
                        triggerSelectionOnTap: true,
                        gridController: controller,
                        itemCount: interestIn.length,
                        gridDelegate:
                            new SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3, childAspectRatio: 0.7),
                        itemBuilder:
                            (BuildContext context, int index, isSelected) {
                          return Stack(
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(4.0),
                                child: GestureDetector(
                                  child: Container(
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(40),
                                        bottomLeft: Radius.circular(40),
                                      ),
                                      image: DecorationImage(
                                        image:
                                            AssetImage(interestIn[index].url),
                                        fit: BoxFit.fill,
                                        colorFilter: ColorFilter.mode(
                                            Colors.red, BlendMode.darken),
                                      ),
                                    ),
                                    height: 180,
                                    width: 200,
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                          left: 25.0, bottom: 10),
                                      child: Center(
                                        child: Align(
                                          alignment: Alignment.bottomLeft,
                                          child: Text(
                                            interestIn[index].name,
                                            style: TextStyle(
                                              fontSize: 20,
                                              color: Colors.white,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              isSelected
                                  ? Positioned(
                                      height: 60,
                                      left: 90,
                                      child: Container(
                                        height: 30,
                                        width: 30,
                                        decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Colors.white,
                                        ),
                                        child: Center(
                                          child: Icon(
                                            Icons.check_outlined,
                                            size: 18,
                                            color: Colors.red,
                                          ),
                                        ),
                                      ),
                                    )
                                  : Container()
                            ],
                          );
                        }),

这是我的代码的结果.....

代码的结果

标签: flutterdart

解决方案


这是我会做的

InterestModel,我创建属性isSelected然后方法.toJson()和工厂方法InterestModel.fromJson(Map json)json序列化

每次用户选择. InterestModel_isSelectedSharedPreferencejsonEncode(interestIn)

如果我想检索列表,请解码字符串,jsonDecode(yourString)然后对其进行迭代并应用InterestModel.fromJson(iteratedString)

代码示例(我没有尝试过):

兴趣模型类

class InterestModel {
  String assetUrl;
  String name;
  bool isSelected;
  InterestModel({this.assetUrl, this.name, this.isSelected});
  
  
  Map toJson() {
    return {
      "assetUrl": assetUrl,
      "name": name,
      "isSelected": isSelected
    };
  }
  
  factory InterestModel.fromJson(Map json) {
    return InterestModel(
      assetUrl: json["assetUrl"],
      name: json["name"],
      isSelected: json["isSelected"]
    );
  }
}

要将其保存到 SharedPreference 中,请确保更新列表值

Future<List<InterestModel>> retrieveInterests() async {
  SharedPreferences pref = await SharedPreferences.getInstance();
  String interestString = await pref.getString("interest_list");
  List jsonArray = jsonDecode(interestString);
  List<InterestModel> interests = [];
  for (json in jsonArray) {
    interests.add(InterestModel.fromJson(json));
  }
  return interests;
}

Future<void> saveToSharedPref(List<InterestModel> interests) async {
  SharedPreferences pref = await SharedPreferences.getInstance();
  await pref.setString("interest_list", jsonEncode(interests));
}

推荐阅读