Flutter:在Swiper中完成特定的逻辑后(在GridView中也设置了GridView),如何显示下一个索引? [英] Flutter : how to show next index after complete a specific logic in Swiper, where GridView also set in Swiper?

查看:64
本文介绍了Flutter:在Swiper中完成特定的逻辑后(在GridView中也设置了GridView),如何显示下一个索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试文字游戏.首先,索引将为白色.如果用户单击正确的答案,则索引将为绿色,然后转到下一个屏幕,索引也会在下一个屏幕中显示为白色..再次,如果用户单击错误的答案,索引将为红色,并且不要放开直到用户输入正确答案...

I'm trying to make a word game. First of all, the index will be white. if user Click the correct answer then index will be to green color and go to next screen, also index will be white in next screen.. again if user click incorrect answer then index will be to red color and don't let go to the next page until user put correct answer...

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

i set a GridView in Swiper (Swiper took by importing, import 'package:flutter_swiper/flutter_swiper.dart';). and i want to show next index of Swiper after completing a logic in GridView. suppose, i have a long string list(array) and took four value string from this list(array) by random, this four values string set in GridView index.

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

Again i make a new string list(array) by this four value string and took a value from this new string list(array) by random, this single string set in Swiper. finally if user can select the Swiper index value to the GridView four index value correctly, then user can see next screen in Swiper. but output is not working properly. problem is - at first i set white color in GridView index, if it is correct answer should be green color in GridView index and incorrect will be red color in GridView index. here is my logic made it messy.

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函数更改为更简单的代码.您不应该验证索引的每个数字,因为索引已经是那个数字

so first thing you should do is changing your onTap function in your gesture detector into a simpler code You shouldn't verify every single number for the index because the index is already that number

要清楚一点,当您调用list [index]时,此处的索引是整数,因此如果index == 1则您正在调用list [1],如果index == 5则您正在调用list [5]您不必测试index == 1还是类似的东西

To be more clear when you call list[index] the index here is an integer so if the index==1 you're calling list[1] and if the index==5 you're calling list[5] you don't have to test if index==1 or something like that

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

so your code should be something like this

 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((){});
          }
        },

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

And next for the problem of testing if the answer is correct or not and color changing and going to next screen

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

First thing please move these lines in your item builder function into a function you can call from anywhere like this for example

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();
}

,您可以在调用dialog.Alert后将_showCorrectAndIncorrectDialog(...)更改为

and you can call this question after calling your dialogAlert if you change the line when you call _showCorrectAndIncorrectDialog(...) into

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

注意:

-请记住在类中声明所需的变量,以便在newQuestion函数中对其进行更改

-Remember to declare the variables you need in your class so they get changed in newQuestion function

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

-First time you lunch the app the variables like " oneValueRandomGet " are gonna be null so you can't show any data, call oneQuestion() in your initState so that when launching the app you get your first question ready directly.

我希望所有这些都不会使您感到困惑,我已尽力简化并为您提供最简单的编辑和答案,如果您仍然无法解决问题,请您尝试改写代码.并尝试使其尽可能简单.

I hope all this doesn't confuse you I tried my best to simplify and give you the simplest edit and answer possible, please if you're still unable to fix your problem I would really advice you to try to rewrite your code and try to make it as simple as possible.

谢谢.

这篇关于Flutter:在Swiper中完成特定的逻辑后(在GridView中也设置了GridView),如何显示下一个索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆