Flutter: ¿cómo mostrar el siguiente índice después de completar una lógica específica en Swiper, donde GridView también se establece en Swiper?
Estoy intentando hacer un juego de palabras. Primero que nada, el índice será blanco. si el usuario hace clic en la respuesta correcta, el índice será de color verde y pasará a la siguiente pantalla, también el índice será blanco en la siguiente pantalla ... nuevamente, si el usuario hace clic en la respuesta incorrecta, el índice será de color rojo y no lo suelte. página siguiente hasta que el usuario ponga la respuesta correcta ...
configuré un GridView en Swiper (Swiper tomó al importar, importar 'paquete: flutter_swiper / flutter_swiper.dart';). y quiero mostrar el siguiente índice de Swiper después de completar una lógica en GridView. Supongamos que tengo una lista de cadenas larga (matriz) y tomé una cadena de cuatro valores de esta lista (matriz) al azar, esta cadena de cuatro valores establecida en el índice GridView.
Nuevamente, hago una nueva lista de cadenas (matriz) con esta cadena de cuatro valores y tomé un valor de esta nueva lista de cadenas (matriz) al azar, esta cadena única establecida en Swiper. finalmente, si el usuario puede seleccionar correctamente el valor del índice Swiper en el valor del índice GridView cuatro, entonces el usuario puede ver la siguiente pantalla en Swiper. pero la salida no funciona correctamente. El problema es que, al principio, configuré el color blanco en el índice GridView, si es correcto, la respuesta debería ser el color verde en el índice GridView y la incorrecta será el color rojo en el índice GridView. aquí está mi lógica lo hizo desordenado.
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,
),
),
),
),
),
],
),
),
);
}
);
}
}
Respuestas
así que lo primero que debe hacer es cambiar su función onTap en su detector de gestos a un código más simple No debe verificar cada número para el índice porque el índice ya es ese número
Para ser más claro cuando llama a list [index], el índice aquí es un número entero, por lo que si el índice == 1 está llamando a list [1] y si el índice == 5 está llamando a list [5] no t tengo que probar si index == 1 o algo así
entonces tu código debería ser algo como esto
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((){});
}
},
Y luego para el problema de probar si la respuesta es correcta o no y cambiar de color y pasar a la siguiente pantalla
Primero, mueva estas líneas en la función del generador de elementos a una función que pueda llamar desde cualquier lugar como este, por ejemplo
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();
}
y puede llamar a esta pregunta después de llamar a su dialogAlert si cambia la línea cuando llama a _showCorrectAndIncorrectDialog (...) en
_showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
newQuestion() //**Add this line also**
Notas:
-Recuerde declarar las variables que necesita en su clase para que se cambien en la función newQuestion
-La primera vez que almorza la aplicación, las variables como "oneValueRandomGet" serán nulas, por lo que no puede mostrar ningún dato, llame a oneQuestion () en su initState para que al iniciar la aplicación tenga lista su primera pregunta directamente.
Espero que todo esto no te confunda. Hice todo lo posible para simplificar y darte la edición y respuesta más simples posibles, por favor, si aún no puedes solucionar tu problema, te recomiendo que intentes reescribir tu código e intentar Hágalo lo más simple posible.
Gracias.