Flutter : Swiper에서 특정 논리를 완료 한 후 다음 인덱스를 표시하는 방법은 무엇입니까? GridView도 Swiper에 설정되어 있습니까?

Nov 25 2020

저는 단어 게임을 만들려고합니다. 우선 인덱스가 흰색이됩니다. 사용자가 정답을 클릭하면 색인이 녹색으로 표시되고 다음 화면으로 이동하며, 다음 화면에서도 색인이 흰색이됩니다. 사용자가 정답을 다시 클릭하면 색인이 빨간색이되고 사용자가 정답을 입력 할 때까지 다음 페이지 ...

나는 Swiper에서 GridView를 설정했습니다 (Swiper는 가져 오기, 가져 오기 'package : flutter_swiper / flutter_swiper.dart';). GridView에서 논리를 완료 한 후 Swiper의 다음 인덱스를 표시하고 싶습니다. 긴 문자열 목록 (배열)이 있고이 목록 (배열)에서 4 개의 값 문자열을 무작위로 가져 왔다고 가정합니다.이 4 개의 값 문자열은 GridView 인덱스에 설정되어 있습니다.

다시 저는이 4 개의 값 문자열로 새 문자열 목록 (배열)을 만들고이 새 문자열 목록 (배열)에서 무작위로 값을 가져 왔습니다.이 단일 문자열은 Swiper에 설정되어 있습니다. 마지막으로 GridView 4 인덱스 값에 Swiper 인덱스 값을 올바르게 선택하면 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,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }
);
}
}

답변

1 OussamaBelabbas Nov 25 2020 at 21:22

따라서 가장 먼저해야 할 일은 제스처 감지기의 onTap 함수를 더 간단한 코드로 변경하는 것입니다. 색인이 이미 해당 번호이므로 색인의 모든 단일 번호를 확인해서는 안됩니다.

list [index]를 호출 할 때 더 명확하게하기 위해 여기서 색인은 정수이므로 index == 1이면 list [1]를 호출하고 index == 5이면 list [5]를 호출합니다. 색인 = = 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**

메모 :

-클래스에서 필요한 변수를 선언하여 newQuestion 함수에서 변경되도록하십시오.

-앱을 처음 런치 할 때 "oneValueRandomGet"과 같은 변수가 null이되어 데이터를 표시 할 수 없으므로 initState에서 oneQuestion ()을 호출하여 앱을 시작할 때 첫 번째 질문을 직접 준비 할 수 있도록합니다.

이 모든 것이 당신을 혼란스럽게하지 않기를 바랍니다. 최선을 다해 단순화하고 가능한 가장 간단한 편집과 답변을 제공합니다. 그래도 문제를 해결할 수 없다면 코드를 다시 작성하고 시도해 보도록 조언하겠습니다. 가능한 한 간단하게 만드십시오.

감사합니다.