i think the on Pressed function in elevated button is null but i dont understand why my main file where i am using List and Map to create and switch questions and answers answers are on the buttons and they are printed on them but they are greyed out
import './quiz.dart';
import './result.dart';
void main() => runApp(TestApp());
@override
class TestApp extends StatefulWidget {
const TestApp({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _TestAppState();
}
}
class _TestAppState extends State<TestApp> {
var _i = 0;
final _question = const [
{
'q1': 'whats the capital of India',
'a1': ['Delhi', 'Mumbai', 'Chennai', 'Bangalore'],
},
{
'q1': 'whats the Language of India',
'a1': ['Sanskrit', 'Bengali', 'Hindi', 'Kannada'],
},
{
'q1': 'whats the continent India is located in',
'a1': ['Africa', 'Asia', 'America', 'Australia'],
},
{
'q1': 'whats second most spoken language in India',
'a1': ['Hindi', 'Gujarati', 'Marathi', 'English'],
},
];
_answeredQ() {
setState(() {
_i = _i 1;
});
// return 0;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Test App!"),
),
body: _i < _question.length
? Quiz(qMap: _question, aFunction: _answeredQ(), index: _i)
: Result(),
),
);
}
}
**here's my Quiz class using as a custom widget
import './questionText.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final List<Map<String, Object>> qMap;
final aFunction;
final int index;
Quiz({required this.qMap, required this.aFunction, required this.index});
@override
Widget build(BuildContext context) {
return Column(
children: [
Question(
qMap[index]['q1'],
),
...(qMap[index]['a1'] as List<String>).map((ans) {
return AnswerW(aFunction, ans);
}).toList()
],
);
}
}
and here's the button custom widget class
class AnswerW extends StatelessWidget {
final selAns;
final String answerText;
AnswerW( this.selAns, this.answerText);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: ElevatedButton(onPressed: selAns,
child: Text(answerText),
),
);
}
}
CodePudding user response:
In ? Quiz(qMap: _question, aFunction: _answeredQ(), index: _i)
You are passing the return value of _answeredQ()
, not the actual function itself. You can change this to just _answeredQ
(without the "()") or aFunction: () => _answeredQ()
FWIW It's good in dart to take advantage of strong typing. It provides you with better error messages and better linting. Because you don't have any types for most of your variables they can be anything, and the linter has a hard time trying to figure out if you have a type mismatch.