为什么GetStorage()不保留多个容器的值?

问题描述 投票:0回答:1

我制作了一个容器,通常它是灰色的。然而,如果你

longPress
它,它就会变成绿色。现在,我正在使用
GetStorage()
,对于这个容器,它工作得非常完美。它会写入数据并保存它,这样即使我退出应用程序并重新打开它,我的容器仍然是绿色的。现在我想将这个
longPress
功能添加到我的其他容器中,但我遇到了问题。我创建了 2 个单独的方法,以便为每个容器分配不同的方法,并且每个容器都可以单独运行。然而,
GetStorage
不会保存第二个容器的颜色数据;为什么是这样?我可以长按并更改其颜色,但是当我退出并重新打开应用程序时,颜色不会保存。 2 个容器的代码基本相同,所以我不明白为什么它只适用于容器 1。非常感谢任何有关如何解决此问题的提示!

这是初始化容器1的代码:

late Color colorContainer2 = Colors.white24;
  void initState() {
    colorContainer = Color(
      GetStorage().read<int>('colorContainer') ?? Colors.white24.value,
    );
  }

这是使用

GetStorage
容器 1 的代码:

        InkWell(
            onLongPress: () {
              setState(() {
                colorContainer = colorContainer == Colors.white24
                    ? Colors.green.shade600
                    : Colors.white24;
                GetStorage().write('colorContainer', colorContainer.value);
              });
            },
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const Sune_CLL(),
                ),
              );
            },
            child: Container(
              width: 500,
              color: colorContainer,
              height: 125,
              

初始化容器 2:

late Color colorContainer2 = Colors.white24;

 void initState2() {
    colorContainer2 = Color(
      GetStorage().read<int>('colorContainer2') ?? Colors.white24.value,
    );
  }

-在容器 2 上使用

GetStorage

       InkWell(
            onLongPress: () {
              setState(() {
                colorContainer2 = colorContainer2 == Colors.white24
                    ? Colors.green.shade600
                    : Colors.white24;
                GetStorage().write('colorContainer2', colorContainer2.value);
              });
            },
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const ASune_CLL(),
                ),
              );
            },
            child: Container(
              width: 500,
              color: colorContainer2,
              height: 125,
flutter dart
1个回答
0
投票

您是否在 Statefull 小部件中初始化此容器?有状态的小部件有 initState 函数,所以我认为您的 initState2 在创建小部件时没有调用。

colorContainer2 = Color(
          GetStorage().read<int>('colorContainer2') ?? Colors.white24.value,
        );

将此代码写入 initState 函数中。

© www.soinside.com 2019 - 2024. All rights reserved.