I have a problem with a button in Flutter, as pressing it does not generate any events, and I can't think of any way to fix it.
CODE:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fbutton/fbutton.dart';
import 'package:quiz_cisco1_0/quizprincipal.dart';
void main() => runApp(MyAppState());
class MyAppState extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Cisco Quiz",
home: Scaffold(
extendBodyBehindAppBar: true,
body: SafeArea(
child: Column(
children: [
Center(
child: Image.asset("assets/cisco_logo.png", width: 200, height: 200,),
),
Center(
child: Image.asset("assets/quizz.png", width: 200, height: 200,),
),
Text("La App Perfecta para prepararte", style: TextStyle(fontSize: 19.0,fontWeight: FontWeight.bold)),
Text("en Cisco CCNA 1,2 y 3", style: TextStyle(fontSize: 19.0, fontWeight: FontWeight.bold),),
SizedBox(height: 85.0),
FButton(
width: 185,
height: 60,
alignment: Alignment.center,
text: "Empezar",
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold,fontSize: 20.0),
color: Colors.blue,
onPressed: (){
Navigator.push(context,
MaterialPageRoute(builder:(context) => MyAppsds()));
},
clickEffect: true,
corner: FCorner(
leftBottomCorner: 40,
leftTopCorner: 6,
rightTopCorner: 40,
rightBottomCorner: 6
),
),
],
),
),
),
);
}
}
CODE:
import 'package:flutter/material.dart';
import './quiz.dart';
import './result.dart';
import 'main.dart';
class MyAppsds extends StatefulWidget{
_MyAppState createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyAppsds> {
final _questions = const [
{
'questionText': '1. Un router con un sistema operativo válido contiene un archivo de configuración almacenado en la NVRAM. El archivo de configuración tiene una contraseña secreta de habilitación pero no una contraseña de consola. Cuando el router se inicie, ¿qué modo se mostrará?',
'answers': [
{'text': 'Modo de configuración global', 'score': -2},
{'text': 'Modo de ejecución privilegiado', 'score': -2},
{'text': 'Modo EXEC usuario', 'score': 10},
{'text': 'Modo de configuración', 'score': -2},
],
},
{
'questionText': ' 2.¿Por qué un switch de Capa 2 necesitaría una dirección IP?',
'answers': [
{'text': 'Para permitir que el switch envíe tramas de broadcast a los PCs conectados', 'score': -2},
{'text': 'Para permitir que el switch funcione como una puerta de enlace por defecto', 'score': -2},
{'text': 'Para permitir que el switch reciba tramas de los PCs conectados', 'score': -2},
{
'text':
'Para permitir que el switch sea administrado a distancia',
'score': 10
},
],
},
{
'questionText': ' 3.¿Cuál es el SVI por defecto en un switch Cisco?',
'answers': [
{'text': 'VLAN999', 'score': -2},
{'text': 'VLAN1', 'score': 10},
{'text': 'VLAN99', 'score': -2},
{'text': 'VLAN100', 'score': -2},
],
},
{
'questionText': '4.En el comando ‘show running-config’, ¿qué parte de la sintaxis está representada por ‘running-config’?',
'answers': [
{'text': 'Una palabra clave', 'score': 10},
{'text': 'El comando', 'score': -2},
{'text': 'Una variable', 'score': -2},
{'text': 'Un aviso', 'score': -2},
],
},
{
'questionText': '5.¿Qué tipo de tráfico de red requiere QoS?',
'answers': [
{'text': 'Video conferencia', 'score': 10},
{'text': 'Compra en línea', 'score': -2},
{'text': 'Wiki', 'score': -2},
{'text': 'Correo electrónico', 'score': -2},
],
},
{
'questionText': '6.¿En qué capa del modelo OSI se añadiría una dirección lógica durante el encapsulamiento?',
'answers': [
{'text': 'Capa física', 'score': -2},
{'text': 'Capa de enlace de datos', 'score': -2},
{'text': 'Capa de red', 'score': 10},
{'text': 'Capa de transporte', 'score': -2},
],
},
];
var _questionIndex = 0;
var _totalScore = 0;
void _resetQuiz() {
setState(() {
_questionIndex = 0;
_totalScore = 0;
});
}
void _answerQuestion(int score) {
_totalScore += score;
setState(() {
_questionIndex = _questionIndex + 1;
});
print(_questionIndex);
if (_questionIndex < _questions.length) {
print('We have more questions!');
} else {
print('No more questions!');
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Quiz Cisco'),
flexibleSpace: Image(
image: AssetImage('assets/banner.jpg'),
fit: BoxFit.cover,
),
backgroundColor: Colors.transparent,
),
body: Padding(
padding: const EdgeInsets.all(30.0),
child: _questionIndex < _questions.length
? Quiz(
answerQuestion: _answerQuestion,
questionIndex: _questionIndex,
questions: _questions,
) //Quiz
: Result(_totalScore, _resetQuiz),
), //Padding
), //Scaffold
debugShowCheckedModeBanner: false,
); //MaterialApp
}
}
error:
Exception caught by gesture
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
When the exception was thrown, this was the stack:
#0 Navigator.of. (package:flutter/src/widgets/navigator.dart:2711:9)
#1 Navigator.of (package:flutter/src/widgets/navigator.dart:2718:6)
#2 Navigator.push (package:flutter/src/widgets/navigator.dart:2116:22)
#3 MyAppState.build. (package:quiz_cisco1_0/main.dart:37:29)
#4 _FButton.onPressed (package:fbutton/fbutton.dart:561:23)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#665d0
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(184.2, 566.6)
finalLocalPosition: Offset(96.7, 6.1)
button: 1
sent tap down
In MyAppState, the context you're using cannot find the MaterialApp (which includes a default Navigator widget). To have a context with the MaterialApp, separate the Scaffold into a different StatelessWidget.
Sample:
FROM
...
home: Scaffold(
...
TO
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(...);
}
}
Also, in _MyAppState, you can remove the MaterialApp and just return a Scaffold. In MyAppsds, don't forget to put #override in createState().
I would also suggest to change the name of _MyAppState. Recommended name for State classes would be _<StatefulWidget name>State. (setting it to private is optional)
Sample: _MyAppsdsState
Related
It's propably very simple question, but i can't find a solution. How to get a 'Answer 1', 'Answer 2',etc. from this map and put them in to Text widget in loop? I'm trying to make questionnaire and i need to get values of 'text'.
I simplified the code as much as possible:
final questions = const [
{
'questionText': 'This is the first question?',
'answers': [
{'text': 'Answer 1', 'answer': 1},
{'text': 'Answer 2', 'answer': 2},
{'text': 'Answer 3', 'answer': 3},
{'text': 'Answer 4', 'answer': 4},
],
},
{
'questionText': 'This is the second question?',
'answers': [
{'text': 'Answer 1', 'answer': 1},
{'text': 'Answer 2', 'answer': 2},
{'text': 'Answer 3', 'answer': 3},
{'text': 'Answer 4', 'answer': 4}
],
},
];
int numberOfAnswers = 4;
int questionIndex = 0;
Column(
children: [
for (var i = 0; i < numberOfAnswers; i++)
Text('Answer (1,2,3,4)'),
],
),
Tried: questions[questionIndex]['answers']['text'], etc, but it doesn't work.
You can get specific question with questions[index]["questionText"];
and its answer questions[index]["answers"] as List?;
Here is the example
class Fasd4 extends StatelessWidget {
const Fasd4({super.key});
final questions = const [
{
'questionText': 'This is the first question?',
'answers': [
{'text': 'Answer 1', 'answer': 1},
{'text': 'Answer 2', 'answer': 2},
{'text': 'Answer 3', 'answer': 3},
{'text': 'Answer 4', 'answer': 4},
],
},
{
'questionText': 'This is the second question?',
'answers': [
{'text': 'Answer 1', 'answer': 1},
{'text': 'Answer 2', 'answer': 2},
{'text': 'Answer 3', 'answer': 3},
{'text': 'Answer 4', 'answer': 4}
],
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: questions.length,
itemBuilder: (context, index) {
final question = questions[index]["questionText"];
final answers = questions[index]["answers"] as List?;
return Column(
children: [
Container(
height: kToolbarHeight,
color: Colors.deepPurple,
alignment: Alignment.center,
child: Text("$question")),
for (var i = 0; i < (answers?.length ?? 0); i++)
Text(
"text: ${answers?[i]['text']} : answer ${answers?[i]['answer']} "),
],
);
},
));
}
}
It would be better if you create model class for it.
You can access your answers and list them the following way:
class TestWidget extends StatelessWidget {
TestWidget({Key? key}) : super(key: key);
final List<Map<String, dynamic>> questions = [
{
'questionText': 'This is the first question?',
'answers': [
{'text': 'Answer 1', 'answer': 1},
{'text': 'Answer 2', 'answer': 2},
{'text': 'Answer 3', 'answer': 3},
{'text': 'Answer 4', 'answer': 4},
],
},
{
'questionText': 'This is the second question?',
'answers': [
{'text': 'Answer 1', 'answer': 1},
{'text': 'Answer 2', 'answer': 2},
{'text': 'Answer 3', 'answer': 3},
{'text': 'Answer 4', 'answer': 4}
],
},
];
final int numberOfAnswers = 4;
final int questionIndex = 0;
#override
Widget build(BuildContext context) {
return Column(
children: [
for (int i = 0; i < numberOfAnswers; i++) ...[
Text(questions[questionIndex]['answers'][i]['text']),
],
],
);
}
}
Loop through both questions and answers:
for (var question in questions) {
print(question['questionText']);
final answers = question['answers'] as List;
for (var answer in answers) {
print(answer['text']);
}
}
Output:
This is the first question?
Answer 1
Answer 2
Answer 3
Answer 4
This is the second question?
Answer 1
Answer 2
Answer 3
Answer 4
I have a scrollable listView full of quotes, now i want to display a toast message whenever the user scrolled to the bottom of the list. Tight now, I use scroll_edge_listener to detect the scrolling position. I tried to use 'if' condition to create a function to display a toast message, but it does not seem to be working. Really appreciate any help. Anyway, this is my code. Still new to Flutter.
import 'package:flutter/material.dart';
import 'quote.dart';
import 'package:scroll_edge_listener/scroll_edge_listener.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() => runApp(MaterialApp(
home: QuoteList(),
));
class QuoteList extends StatefulWidget {
#override
_QuoteListState createState() => _QuoteListState();
}
class _QuoteListState extends State<QuoteList> {
final controller = ScrollController(); //For detecting sroll activity
int index = 0;
List<Quote> quotes = [
Quote(author: 'Osca Wilde', text: '1'),
Quote(author: 'Oscar Wilde', text: '2'),
Quote(author: 'Osca Wilde', text: '3'),
Quote(author: 'Oscar Wilde', text: '4'),
Quote(author: 'Osca Wilde', text: '5'),
Quote(author: 'Oscar Wilde', text: '6'),
Quote(author: 'Osca Wilde', text: '7'),
Quote(author: 'Oscar Wilde', text: '8'),
Quote(author: 'Oscar Wilde', text: '6'),
Quote(author: 'Osca Wilde', text: '7'),
Quote(author: 'Oscar Wilde', text: '8'),
];
Widget quoteTemplate(quote) {
return Card(
margin: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0.0),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
quote.text,
style: TextStyle(
fontSize: 18.0,
color: Colors.grey[800],
),
),
SizedBox(height: 6.0),
Text(
quote.author,
style: TextStyle(
fontSize: 14.0,
color: Colors.grey[800],
),
)
],
),
),
);
}
var refreshKey = GlobalKey<RefreshIndicatorState>();
#override
void initState() {
super.initState();
controller.addListener(listenScrolling);
}
void listenScrolling() {
if (controller.position.atEdge) {
final isTop = controller.position.pixels == 0;
if (isTop) {
Fluttertoast.showToast(
msg: "This is top of the list",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
} else {
Fluttertoast.showToast(
msg: "This is bottom of the list",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
appBar: AppBar(
title: Text('Awesome Quotes'),
centerTitle: true,
backgroundColor: Colors.redAccent,
),
body: RefreshIndicator(
key: refreshKey,
onRefresh: refreshlist,
child: ListView(
children: quotes.map((quote) => quoteTemplate(quote)).toList(),
),
),
);
}
Future<void> refreshlist() async {
refreshKey.currentState?.show(atTop: false);
await Future.delayed(Duration(seconds: 1));
quotes.shuffle();
setState(() {});
}
}
My quote.dart model class
class Quote {
String text;
String author;
Quote({required this.text, required this.author});
}
in which scroll do you use your controller? You should use it in your ListView.
please can any one help me?
Text.rich widget does not work successfully with arabic text. there are a problem with the text direction.
lets give an example
when i run the app the order of the container in the below code is come reverse
that is a big problem for me
Text.rich(
TextSpan(
children: [
TextSpan(text: 'بِسۡمِ ٱللَّهِ ٱلرَّحۡمَٰنِ ٱلرَّحِيمِ'),
WidgetSpan(
child: Container(
width: 30,
height: 30,
color: Colors.green,child:Text('1'),
),
),
TextSpan(text: 'ٱلۡحَمۡدُ لِلَّهِ رَبِّ ٱلۡعَٰلَمِينَ'),
WidgetSpan(
child: Container(
width: 30,
height: 30,
color: Colors.blue,child:Text('2'),
),
),
TextSpan(text: 'ٱلرَّحۡمَٰنِ ٱلرَّحِيمِ'),
WidgetSpan(
child: Container(
width: 30,
height: 30,
color: Colors.red,child:Text('3'),
),
),
],
),
textDirection: TextDirection.rtl,
)
That's because you are WidgetSpans between TextSpans which ruins the TextDirection because WidgetSpan does not follow the directionality,
you can replace the WidgetSpan with a TextSpan and it will work I tested id
Text.rich(
TextSpan(
children: [
TextSpan(text: 'بِسۡمِ ٱللَّهِ ٱلرَّحۡمَٰنِ ٱلرَّحِيمِ'),
TextSpan(text: ' 1 ', style: TextStyle(
backgroundColor: Colors.green,
)),
TextSpan(text: 'ٱلۡحَمۡدُ لِلَّهِ رَبِّ ٱلۡعَٰلَمِينَ'),
TextSpan(text: ' 2 ', style: TextStyle(
backgroundColor: Colors.blue,
)),
TextSpan(text: 'ٱلرَّحۡمَٰنِ ٱلرَّحِيمِ'),
TextSpan(text: ' 3 ', style: TextStyle(
backgroundColor: Colors.red,
)),
],
),
style: TextStyle(
fontFamily: 'UthmanicHafs1'
),
textDirection: TextDirection.rtl,
),
Sometimes the most difficult problems can be solved by very simple things.
There may be many long and difficult ways to solve this problem.
[https://github.com/flutter/flutter/issues/54400#issuecomment-662558160][1]
But the simplest way that i found is
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Quran',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Quran Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Widget> wrapList(List m) {
List<Widget> myList = [];
for (var i in m) {
String a = i['text'] as String;
int b = i['num'];
List l2 = a.split(' ');
myList.addAll(List.generate(l2.length, (e) {
return Text(
e == l2.length - 1 ? '${l2[e]}' : '${l2[e]} ',
style: const TextStyle(fontSize: 18),
);
}));
myList.add(
Container(
alignment: Alignment.center,
width: 20,
height: 20,
child: Text("$b"),
decoration: const BoxDecoration(
color: Colors.green,
),
),
);
}
return myList;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Wrap(
children: wrapList([
{'text': 'بِسۡمِ ٱللَّهِ ٱلرَّحۡمَٰنِ ٱلرَّحِيمِ', 'num': 1},
{'text': 'ٱلۡحَمۡدُ لِلَّهِ رَبِّ ٱلۡعَٰلَمِينَ', 'num': 2},
{'text': 'ٱلرَّحۡمَٰنِ ٱلرَّحِيمِ', 'num': 3},
{'text': 'مَٰلِكِ يَوۡمِ ٱلدِّينِ', 'num': 4},
{'text': 'إِيَّاكَ نَعۡبُدُ وَإِيَّاكَ نَسۡتَعِينُ', 'num': 5},
{'text': 'ٱهۡدِنَا ٱلصِّرَٰطَ ٱلۡمُسۡتَقِيمَ', 'num': 6},
{
'text':
'صِرَٰطَ ٱلَّذِينَ أَنۡعَمۡتَ عَلَيۡهِمۡ غَيۡرِ ٱلۡمَغۡضُوبِ عَلَيۡهِمۡ وَلَا ٱلضَّآلِّينَ',
'num': 7
},
]),
textDirection: TextDirection.rtl,
crossAxisAlignment: WrapCrossAlignment.center,
),
),
);
}
}
I am getting this error in my home.dart file
lib/home.dart(115,29): error G44692867: A value of type 'Object?' can't be assigned to a variable of type 'bool'. [E:\Prajwal\flutter_projects\quiz_app2\build\windows\flutter\flutter_assemble.vcxproj]
lib/home.dart:1
lib/home.dart(125,43): error GC2F972A8: The argument type 'Object?' can't be assigned to the parameter type 'bool'. [E:\Prajwal\flutter_projects\quiz_app2\build\windows\flutter\flutter_assemble.vcxproj]
lib/home.dart:1
lib/home.dart(115,21): error GC2F972A8: The argument type 'MaterialColor?' can't be assigned to the parameter type 'Color' because 'MaterialColor?' is nullable and 'Color' isn't. [E:\Prajwal\flutter_projects\quiz_app2\build\windows\flutter\flutter_assemble.vcxproj]
This is my home.dart file..
import 'package:quiz_app2/answer.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Icon> _scoreTracker = [];
int _questionIndex = 0;
int _totalScore = 0;
bool answerWasSelected = false;
bool endOfQuiz = false;
bool correctAnswerSelected = false;
void _questionAnswered(bool answerScore) {
setState(() {
// answer was selected
answerWasSelected = true;
// check if answer was correct
if (answerScore) {
_totalScore++;
correctAnswerSelected = true;
}
// adding to the score tracker on top
_scoreTracker.add(
answerScore
? Icon(
Icons.check_circle,
color: Colors.green,
)
: Icon(
Icons.clear,
color: Colors.red,
),
);
//when the quiz ends
if (_questionIndex + 1 == _questions.length) {
endOfQuiz = true;
}
});
}
void _nextQuestion() {
setState(() {
_questionIndex++;
answerWasSelected = false;
correctAnswerSelected = false;
});
// what happens at the end of the quiz
if (_questionIndex >= _questions.length) {
_resetQuiz();
}
}
void _resetQuiz() {
setState(() {
_questionIndex = 0;
_totalScore = 0;
_scoreTracker = [];
endOfQuiz = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
' Quiz App',
style: TextStyle(color: Colors.white),
),
centerTitle: true,
),
body: Center(
child: Column(
children: [
Row(
children: [
if (_scoreTracker.length == 0)
SizedBox(
height: 25.0,
),
if (_scoreTracker.length > 0) ..._scoreTracker
],
),
Container(
width: double.infinity,
height: 130.0,
margin: EdgeInsets.only(bottom: 10.0, left: 30.0, right: 30.0),
padding: EdgeInsets.symmetric(horizontal: 50.0, vertical: 20.0),
decoration: BoxDecoration(
color: Colors.deepOrange,
borderRadius: BorderRadius.circular(10.0),
),
child: Center(
child: Text(
_questions[_questionIndex]['question'] as String,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
...(_questions[_questionIndex]['answers']
as List<Map<String, Object>>)
.map(
(answer) => Answer(
answerText: answer['answerText'] as String,
answerColor: answerWasSelected
? answer['score']
? Colors.green
: Colors.red
: null,
answerTap: () {
// if answer was already selected then nothing happens onTap
if (answerWasSelected) {
return;
}
//answer is being selected
_questionAnswered(answer['score']);
},
),
),
SizedBox(height: 20.0),
ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: Size(double.infinity, 40.0),
),
onPressed: () {
if (!answerWasSelected) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
'Please select an answer before going to the next question'),
));
return;
}
_nextQuestion();
},
child: Text(endOfQuiz ? 'Restart Quiz' : 'Next Question'),
),
Container(
padding: EdgeInsets.all(20.0),
child: Text(
'${_totalScore.toString()}/${_questions.length}',
style: TextStyle(fontSize: 40.0, fontWeight: FontWeight.bold),
),
),
if (answerWasSelected && !endOfQuiz)
Container(
height: 100,
width: double.infinity,
color: correctAnswerSelected ? Colors.green : Colors.red,
child: Center(
child: Text(
correctAnswerSelected
? 'Well done, you got it right!'
: 'Wrong :/',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
if (endOfQuiz)
Container(
height: 100,
width: double.infinity,
color: Colors.black,
child: Center(
child: Text(
_totalScore > 4
? 'Congratulations! Your final score is: $_totalScore'
: 'Your final score is: $_totalScore. Better luck next time!',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: _totalScore > 4 ? Colors.green : Colors.red,
),
),
),
),
],
),
),
);
}
}
final _questions = const [
{
'question': 'How long is New Zealand’s Ninety Mile Beach?',
'answers': [
{'answerText': '88km, so 55 miles long.', 'score': true},
{'answerText': '55km, so 34 miles long.', 'score': false},
{'answerText': '90km, so 56 miles long.', 'score': false},
],
},
{
'question':
'In which month does the German festival of Oktoberfest mostly take place?',
'answers': [
{'answerText': 'January', 'score': false},
{'answerText': 'October', 'score': false},
{'answerText': 'September', 'score': true},
],
},
{
'question': 'Who composed the music for Sonic the Hedgehog 3?',
'answers': [
{'answerText': 'Britney Spears', 'score': false},
{'answerText': 'Timbaland', 'score': false},
{'answerText': 'Michael Jackson', 'score': true},
],
},
{
'question': 'In Georgia (the state), it’s illegal to eat what with a fork?',
'answers': [
{'answerText': 'Hamburgers', 'score': false},
{'answerText': 'Fried chicken', 'score': true},
{'answerText': 'Pizza', 'score': false},
],
},
{
'question':
'Which part of his body did musician Gene Simmons from Kiss insure for one million dollars?',
'answers': [
{'answerText': 'His tongue', 'score': true},
{'answerText': 'His leg', 'score': false},
{'answerText': 'His butt', 'score': false},
],
},
{
'question': 'In which country are Panama hats made?',
'answers': [
{'answerText': 'Ecuador', 'score': true},
{'answerText': 'Panama (duh)', 'score': false},
{'answerText': 'Portugal', 'score': false},
],
},
{
'question': 'From which country do French fries originate?',
'answers': [
{'answerText': 'Belgium', 'score': true},
{'answerText': 'France (duh)', 'score': false},
{'answerText': 'Switzerland', 'score': false},
],
},
{
'question': 'Which sea creature has three hearts?',
'answers': [
{'answerText': 'Great White Sharks', 'score': false},
{'answerText': 'Killer Whales', 'score': false},
{'answerText': 'The Octopus', 'score': true},
],
},
{
'question': 'Which European country eats the most chocolate per capita?',
'answers': [
{'answerText': 'Belgium', 'score': false},
{'answerText': 'The Netherlands', 'score': false},
{'answerText': 'Switzerland', 'score': true},
],
},
];
It seems that the error happens in this expression:
answerColor: answerWasSelected
? answer['score']
? Colors.green
: Colors.red
: null,
When you call answer['score'], there is a possibility that the returned value is null, hence you cannot use it as a boolean expression.
If the expected score property is boolean, you could use the null coalescing operator.
answerColor: answerWasSelected
? answer['score'] ?? false // If answer['score'] is null, returns false
? Colors.green
: Colors.red
: null,
I am making a quiz app in flutter which has multiple subjects in grid view. Each grid redirect to a screen which fetch data from a list one by one.
What I want to do : Whenever I click to a grid view, it redirect me to a single screen and fetch data from the respective list.
I want to go to a single screen whenever I click on the grid view but it should show data from the list with respect to grid view user click.
Grid view example
This is grid view example and each number represent a different subject.
final first = const [
{
'question': 'How long is New Zealand’s Ninety Mile Beach?',
'answers': [
{'answerText': '88km, so 55 miles long.', 'score': true},
{'answerText': '55km, so 34 miles long.', 'score': false},
{'answerText': '90km, so 56 miles long.', 'score': false},
],
},
{
'question':
'In which month does the German festival of Oktoberfest mostly take place?',
'answers': [
{'answerText': 'January', 'score': false},
{'answerText': 'October', 'score': false},
{'answerText': 'September', 'score': true},
],
},
{
'question': 'Who composed the music for Sonic the Hedgehog 3?',
'answers': [
{'answerText': 'Britney Spears', 'score': false},
{'answerText': 'Timbaland', 'score': false},
{'answerText': 'Michael Jackson', 'score': true},
],
},
];
final second = const [
{
'question': 'In Georgia (the state), it’s illegal to eat what with a fork?',
'answers': [
{'answerText': 'Hamburgers', 'score': false},
{'answerText': 'Fried chicken', 'score': true},
{'answerText': 'Pizza', 'score': false},
],
},
{
'question':
'Which part of his body did musician Gene Simmons from Kiss insure for one million dollars?',
'answers': [
{'answerText': 'His tongue', 'score': true},
{'answerText': 'His leg', 'score': false},
{'answerText': 'His butt', 'score': false},
],
},
{
'question': 'In which country are Panama hats made?',
'answers': [
{'answerText': 'Ecuador', 'score': true},
{'answerText': 'Panama (duh)', 'score': false},
{'answerText': 'Portugal', 'score': false},
],
},
{
'question': 'From which country do French fries originate?',
'answers': [
{'answerText': 'Belgium', 'score': true},
{'answerText': 'France', 'score': false},
{'answerText': 'Switzerland', 'score': false},
],
},
];
Wrap your code with a gesture detector.
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return GridView.count(
// Create a grid with 2 columns. If you change the scrollDirection to
// horizontal, this produces 2 rows.
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
// Generate 100 widgets that display their index in the List.
children: List.generate(5, (index) {
return GestureDetector(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => NewQuestionPage(
questionId: index.toString(),
)));
},
child: Container(
color: Colors.green,
height: 100,
child: Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.headline5,
),
),
),
);
}),
);
;
}
}
class NewQuestionPage extends StatelessWidget {
final String? questionId;
const NewQuestionPage({Key? key, this.questionId}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Questions"),
),
body: Center(child: Text(questionId!)),
);
}
}