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

Flutter : how to show next index after complete a specific logic in Swiper, where GridView also set in Swiper?

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

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

我再次通过这个四值字符串创建一个新的字符串列表(数组),并随机从这个新的字符串列表(数组)中取一个值,这个单个字符串在 Swiper 中设置。最后,如果用户可以 select 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] 时,这里的索引是一个整数,所以如果 index==1 你调用的是 list[1],如果 index==5 你调用的是 list[ 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();
}

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

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

备注:

-记得在 class 中声明您需要的变量,以便它们在 newQuestion 函数中得到更改

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

我希望这一切不会让你感到困惑我尽力简化并尽可能给你最简单的编辑和答案,如果你仍然无法解决你的问题我真的建议你尝试重写您的代码并尽量使其尽可能简单。

谢谢。