Flutter:如何在Swiper中完成特定逻辑后显示下一个索引,其中GridView也在Swiper中设置?

2023-12-09

我正在尝试制作一个文字游戏。首先,索引将是白色的。如果用户单击正确的答案,则索引将变为绿色并进入下一个屏幕,并且下一个屏幕中的索引将为白色。再次,如果用户单击不正确的答案,则索引将变为红色,并且不要放开下一页直到用户输入正确答案...

我在 Swiper 中设置了一个 GridView (Swiper 通过导入获取, 导入'包:flutter_swiper/flutter_swiper.dart';)。 我想在 GridView 中完成逻辑后显示 Swiper 的下一个索引。假设,我有一个长字符串列表(数组),并从该列表(数组)中随机取出四个值字符串,这四个值字符串在 GridView 索引中设置。

我再次通过这个四值字符串创建一个新的字符串列表(数组),并随机从这个新的字符串列表(数组)中获取一个值,这个单个字符串在 Swiper 中设置。最后,如果用户可以正确地将 Swiper 索引值选择为 GridView 的四个索引值,则用户可以在 Swiper 中看到下一个屏幕。但输出无法正常工作。问题是 - 首先我在 GridView 索引中设置白色,如果正确答案应该是 GridView 索引中的绿色,不正确的答案应该是 GridView 索引中的红色。这是我的逻辑让它变得混乱。

import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:math';

class GameWordRoute extends StatefulWidget {
@override
 _GameWordRouteState createState() => _GameWordRouteState(); }

class _GameWordRouteState extends State<GameWordRoute> {

SwiperController _controller = SwiperController();
SwiperControl _control = SwiperControl(color: Colors.white);

double get _width => MediaQuery.of(context).size.width;
double get _height => MediaQuery.of(context).size.height;

bool inLastPage = true;
bool _answer = false;

List<Color> colorList = <Color>[Colors.white, Colors.white, Colors.white, Colors.white,];
List<String> gameButtonList = <String>[];

FlutterTts flutterTts = FlutterTts();

@override
Widget build(BuildContext context) {

var sizeDevice = MediaQuery.of(context).size;
final orientation = MediaQuery.of(context).orientation;

final double itemHeight = sizeDevice.width / 6;
final double itemWidth = sizeDevice.width / 2;

return Scaffold(
  backgroundColor: Colors.purple, // white
  body: SafeArea(
    child: Column(
      children: <Widget>[
        Expanded(
            flex: 1,
            child: Container(
              color: Colors.lightBlueAccent,
            )),
        Expanded(
          flex: 8,
          child: Container(
            color: Colors.cyan,
            child: Swiper(
              controller: _controller,
              loop: false,
              scrollDirection: Axis.horizontal,
              itemCount: word_data.drink.length,
              onIndexChanged: (value) {
                if (value == word_data.drink.length - 1)
                  setState(() {
                    inLastPage = true;
                  });
                else {
                  setState(() {
                    inLastPage = true;  // false
                  });
                }
              },
              itemBuilder: (BuildContext context, int index) {
                gameButtonList.clear();
                var fourValueRandom = new Random();

                for (var i = 0; i < 4; i++) {
                  final fourGameBtnRandom = word_data.drink[fourValueRandom.nextInt(word_data.drink.length)];
                  gameButtonList.add(fourGameBtnRandom);
                }

                var oneValueRandom = new Random();
                var oneValueRandomGet = gameButtonList[oneValueRandom.nextInt(gameButtonList.length)];
                var wordDataReplace = oneValueRandomGet.replaceAll(" ", "_").toLowerCase();
                return Container(
                  child: Column(
                    children: <Widget>[
                      Expanded(
                          flex: 8,
                          child: Container(
                            color: Colors.purple,
                            width: _width,
                            alignment: Alignment.center,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: Image.asset("asset/drink_images/" + wordDataReplace + ".png",
                                fit: BoxFit.contain,
                              ),
                            ),
                          )),
                      Expanded(
                          flex: 1,
                          child: Container(
                            color: Colors.yellow,
                            width: _width,
                            alignment: Alignment.center,
                            // "${categoryTitleArray[index]}"
                            child: Text("What is this?"),
                          )),
                      Expanded(
                          flex: 4,
                          child: Container(
                            color: Colors.yellow[200],
                            width: _width,
                            alignment: Alignment.center,
                            child: GridView.builder(
                                padding: EdgeInsets.all(8),
                                itemCount: 4,
                                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: (orientation == Orientation.portrait) ? 2 : 4,
                                  crossAxisSpacing: 5,
                                  mainAxisSpacing: 5,
                                  childAspectRatio: (itemWidth / itemHeight),
                                ),
                                itemBuilder: (BuildContext context, int index) {
                                  return GestureDetector(
                                    onTap: () {
                                      if (index == 0) {
                                        if (gameButtonList[0] == oneValueRandomGet){
                                          _answer = true;
                                          inLastPage = false;
                                          colorList[0] = Colors.green;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);

                                        }else{
                                          colorList[0] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }

                                      } else if (index == 1) {

                                        if (gameButtonList[1] == oneValueRandomGet){
                                          _answer = true;
                                          colorList[1] = Colors.green;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
                                          inLastPage = false;
                                        }else{
                                          colorList[1] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }

                                      } else if (index == 2) {
                                        if (gameButtonList[2] == oneValueRandomGet){
                                          _answer = true;
                                          colorList[2] = Colors.green;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
                                          inLastPage = false;
                                        }else{
                                          colorList[2] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }
                                      } else if (index == 3) {

                                        if (gameButtonList[3] == oneValueRandomGet){
                                          _answer = true;
                                          colorList[3] = Colors.green;
                                          inLastPage = false;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
                                        }else{
                                          colorList[3] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }
                                      }
                                    },
                                    child: Container(
                                      child: new Card(
                                        elevation: 0,
                                        color: colorList[index], //Colors.transparent,
                                        child: Center(
                                          child: Text(
                                            "${gameButtonList[index]}",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(color: Colors.black),
                                          ),
                                        ),
                                      ),
                                    ),
                                  );
                                }),
                          )),
                    ],
                  ),
                );
              },
            ),
          ),
        ),
        Expanded(
            flex: 1,
            child: Container(
              color: Colors.lightBlueAccent,
            )),
      ],
    ),
  ),
);
}

void _showCorrectAndIncorrectDialog(String _title, String _image, String _subTitle, Color _color){

showDialog(
    context: context,
    builder: (BuildContext context){
      Future.delayed(Duration(milliseconds: 500), () {
        Navigator.of(context).pop(true);
      });
      return AlertDialog(
        title: Text(_title, textAlign: TextAlign.center, style: TextStyle(color: _color),),
        content: Container(
          height: _width/1.1,
          child: Column(
            children: <Widget>[
              Expanded(
                flex: 4,
                child: Container(
                  // color: Colors.cyan[100],
                  child: Image.asset(_image,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(height: 8),
              Expanded(
                flex: 1,
                child: Container(
                  color: Colors.cyan,
                  child: Center(
                    child: Text(
                      _subTitle,
                      style: TextStyle(
                        // fontSize: 24,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }
);
}
}

所以你应该做的第一件事是将手势检测器中的 onTap 函数更改为更简单的代码你不应该验证索引的每个数字,因为索引已经是该数字

更清楚地说,当您调用 list[index] 时,此处的索引是一个整数,因此如果您调用 list[1] 的索引==1,并且您调用 list[5] 的索引==5,则您不需要不必测试index==1或类似的东西

所以你的代码应该是这样的

 onTap: () async{
       if (gameButtonList[index] == oneValueRandomGet){
          _answer = true;
          colorList[index] = Colors.green;
          inLastPage = false;
          setState((){});
          
          _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
          }else{
          colorList[index] = Colors.red;
          inLastPage = true;
          setState((){});
          }
        },

接下来是测试答案是否正确以及颜色变化并进入下一个屏幕的问题

首先,请将项目构建器函数中的这些行移动到可以从任何地方调用的函数中,例如

void newQuestion(){
gameButtonList.clear();
var fourValueRandom = new Random();
for (var i = 0; i < 4; i++) {
final fourGameBtnRandom =     word_data.drink[fourValueRandom.nextInt(word_data.drink.length)];
gameButtonList.add(fourGameBtnRandom);
}
oneValueRandomGet = gameButtonList[fourValueRandom.nextInt(gameButtonList.length)];
wordDataReplace = oneValueRandomGet.replaceAll(" ", "_").toLowerCase();
}

如果您在调用 _showCorrectAndIn CorrectDialog(...) 时更改行,则可以在调用dialogAlert后调用此问题

_showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
newQuestion() //**Add this line also**

Notes :

-记住在类中声明您需要的变量,以便它们在 newQuestion 函数中进行更改

- 第一次启动应用程序时,像“ oneValueRandomGet ”这样的变量将为空,因此您无法显示任何数据,请在 initState 中调用 oneQuestion() ,以便在启动应用程序时直接准备好第一个问题。

我希望所有这些不会让您感到困惑,我尽力简化并为您提供最简单的编辑和答案,如果您仍然无法解决您的问题,我真的建议您尝试重写代码并尝试让它尽可能简单。

谢谢。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter:如何在Swiper中完成特定逻辑后显示下一个索引,其中GridView也在Swiper中设置? 的相关文章

随机推荐