使用 PageView.builder 索引更改容器颜色并使用颜色列表设置状态

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

我需要的只是主父容器在用户转到不同页面时更改颜色,但无论我尝试什么都不会改变。

class AppCardColors {
  static Color? orange = Colors.orange[500];
  static Color? blue = Colors.blue[700];
  static Color? red = Colors.red[600];

  static List<Color?> colorsList = [
    Colors.orange[500],
    Colors.blue[700],
    Colors.red[600],
  ];
}

上面的类是我从中得到我想要的颜色的类,正如你所看到的,我想要 colorsList 变量中的颜色。

//ignore: must_be_immutable
class MyWidget extends StatefulWidget {
  MyWidget({required this.child, Key? key}) : super(key: key);
  Widget child;

  @override
  State<MyWidget createState() => _MyWidgetState();
}

class _QuestionMainTemplateState extends State<QuestionMainTemplate> {
  @override
  Widget build(BuildContext context) {
    PageController pageController = PageController();
    int colorIndex = 0;

    return Scaffold(
      body: SizedBox(
        height: double.maxFinite,
        width: double.maxFinite,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Container(
              width: double.maxFinite,
              height: double.maxFinite,
              color: AppCardColors.colorsList[colorIndex], //where i want the color to change
            ),
            Positioned(
              left: 20,
              top: 50,
              child: IconButton(
                onPressed: () {},
                icon: const Icon(
                  color: Colors.white,
                  size: 30,
                  Icons.exit_to_app_rounded,
                ),
              ),
            ),
            Positioned(
              top: 125,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: 5000,
                child: PageView.builder(
                    controller: pageController,
                    onPageChanged: (index) {
                      setState(() {
                        colorIndex = index % AppCardColors.colorsList.length;
//where the color is chnaged
                        print(colorIndex);
                      });
                    },
                    itemCount: 5,
                    itemBuilder: (_, index) => IrrelevantWidget()),
              ),
            ),
          ],
        ),
      ),
    );
  }
}`

我尝试了各种不同的方法来分配颜色,但直到现在都没有用

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