The element type 'Question' can't be assigned to the list type 'Widget' - flutter

I can't use my own Class/Widget Question() from question.dart to main.dart (ERR Location 3rd line after body):
import 'package:flutter/material.dart';
import './question.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var questionIndex = 0;
// State of function that process data to UI
void _answerQuestion() {
setState(() {
questionIndex = questionIndex + 1;
});
print(questionIndex);
}
void _pangBawas() {
setState(() {
questionIndex = questionIndex - 1;
});
print(questionIndex);
}
// End of State
// This section is responsible for builing UI
#override
Widget build(BuildContext context) {
var questions = [
'What\'s your favorite color?',
'What\'s your favorite animal?',
'What\'s your favorite food?',
'What\'s your favorite color?',
'What\'s your favorite dress?',
'What\'s your favorite position?',
];
// Start of UI
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question( //ERROR: The element type 'Question' can't be assigned to the list type 'Widget'.
questions[questionIndex],
),
RaisedButton(
child: Text('Answer 1'),
onPressed: _answerQuestion,
),
RaisedButton(
child: Text('Answer 2'),
onPressed: () => _pangBawas,
),
RaisedButton(
child: Text('Answer 3'),
onPressed: () {
//....
print('Hi');
}),
],
),
),
);
// End of UI
}
}
There's no error here, I only get error using Question() on my main.dart file
import 'package:/flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
#override
Widget build(BuildContext context) {
return Container(
child: Text(
questionText,
),
);
}
}

Making use of interpolation solves some errors and displays the error to you in your UI. The code below works just fine:
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questiontext;
Question(this.questiontext);
#override
Widget build(BuildContext context) {
return Text("$questiontext");
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var questionIndex = 0;
// State of function that process data to UI
void _answerQuestion() {
setState(() {
questionIndex = questionIndex + 1;
});
print(questionIndex);
}
void _pangBawas() {
setState(() {
questionIndex = questionIndex - 1;
});
print(questionIndex);
}
// End of State
// This section is responsible for builing UI
#override
Widget build(BuildContext context) {
var questions = [
'What\'s your favorite color?',
'What\'s your favorite animal?',
'What\'s your favorite food?',
'What\'s your favorite color?',
'What\'s your favorite dress?',
'What\'s your favorite position?',
];
// Start of UI
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(
//ERROR: The element type 'Question' can't be assigned to the list type 'Widget'.
"${questions[questionIndex]}",
),
RaisedButton(
child: Text('Answer 1'),
onPressed: _answerQuestion,
),
RaisedButton(
child: Text('Answer 2'),
onPressed: () => _pangBawas,
),
RaisedButton(
child: Text('Answer 3'),
onPressed: () {
//....
print('Hi');
}),
],
),
),
);
// End of UI
}
}

You could add itinerary operator to check If the Widget that is returned from the Question class is null or not. This happens because the Column's children widgets can't be null.
body: Column(
children: [
Question(questions[questionIndex]) == null
? SizedBox()
: Question(questions[questionIndex]),
This way if the widget returned from the Question class is null, then the Column will create a SizedBox instead of the Container + Text.

Related

What is necessary the propagation operator(...), in this code flutter

I get this error when I attempt to compile:
The element type 'Iterable' can't be assigned to the list type 'Widget'.dartlist_element_type_not_assignable.
My code:
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var _questionIndex = 0;
void _answerQuestion() {
setState(() {
_questionIndex = _questionIndex + 1;
print(_questionIndex);
});
}
#override
Widget build(BuildContext context) {
var questions = [
{
'question': 'what is your favourite color',
'answers': ['Black', 'Red', 'Green', 'white']
},
{
'question': 'what is your favourite song',
'answers': ['Thunderstorm', 'AC/DC', 'Mama mia', 'Burriqio']
},
{
'question': 'what is your favourite food',
'answers': ['Macarrones', 'Salmorejo', 'Albondigas', 'Chorizo']
}
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(
questions[_questionIndex]['question'],
),
...(questions[_questionIndex]['answers'] as List<String>).map((answer) {
return Answer(_answerQuestion, answer);
})
],
),
),
);
}
}
I don't understand why I have to use that for add to list. Because isn't the operator for creating a new list with each element mapping with the method map?
Thank you if you can help me.
If you don't use spread operator(...), the result is nested list in your code.
Like below.
body: Column(
children: [
Widget1,
[Widget2, Widget3, ...],
],
),
When you use spread operator, the result will be list of Widget.
body: Column(
children: [
Widget1,
...[Widget2, Widget3, ...],
],
),
is same with below.
body: Column(
children: [
Widget1,
Widget2,
Widget3,
...,
],
),

The method 'map' was called on null

I have a got a problem with the null, I have no idea why.. I'm begginer in the flutter
The method 'map' was called on null.
Receiver: null
Tried calling: map(Closure: (String) => Answer)"
main.dart
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
static const questions = [
{
'questionText': 'Whats your favourite car?',
'answers': ['HYUNDAI', 'BMW', 'KIA', 'AUDI']
},
{
'questionText': 'What is your favourite game?',
'answers': ['CS:GO', 'LOL', 'WOW', 'GTA']
},
{
'questionText': 'What is your favourite phone?',
'answer': ['IPHONE', 'SAMSUNG', 'SONY', 'HUAWEI']
}
];
var _questionIndex = 0;
void _answerQuestion() {
setState(() {
_questionIndex = _questionIndex + 1;
});
if (_questionIndex < questions.length) {
print('We have more questions');
}
print(_questionIndex);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text('Quiz App'),
),
body: _questionIndex < questions.length
? Column(
children: [
Question(
questions[_questionIndex]['questionText'] as String,
),
...(questions[_questionIndex]['answers'] as List<String>)
.map((answer) {
return Answer(_answerQuestion, answer);
}).toList(),
],
)
: Center(child: Text('We finally got it'))),
);
}
}
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: Text(
questionText,
style: TextStyle(fontSize: 22),
textAlign: TextAlign.center,
),
);
}
}
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final VoidCallback selectHandler;
final String answerText;
Answer(this.selectHandler, this.answerText);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red),
),
onPressed: selectHandler,
child: Text(answerText),
));
}
}
enter image description here
Please help me :)
I looked up on a different topics about this, adding ?? to toList () , but still the same error
static const questions = [
{
'questionText': 'Whats your favourite car?',
'answers': ['HYUNDAI', 'BMW', 'KIA', 'AUDI']
},
{
'questionText': 'What is your favourite game?',
'answers': ['CS:GO', 'LOL', 'WOW', 'GTA']
},
{
'questionText': 'What is your favourite phone?',
'answer': ['IPHONE', 'SAMSUNG', 'SONY', 'HUAWEI']
}
];
In the last item, you write answer instead of answers.
Please have a look!

The argument type 'Function' can't be assigned to the parameter type 'void Function()?

I am getting this error on answer.dart
"lib/answer.dart:15:20: Error: The argument type 'Function' can't be assigned to the parameter type 'void Function()?'."
Here are the files:
main.dart
import 'package:flutter/material.dart';
import 'Questions.dart';
import 'answer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyAppState();
// ignore: dead_code
throw UnimplementedError();
}
}
class _MyAppState extends State<MyApp> {
var _questionIndex = 0;
var questions = [
'what\'s your fav color?',
'what\'s your fav Food?',
'what\'s your fav Animal?'
];
void _answerQuestion() {
setState(() {
_questionIndex++;
if (_questionIndex >= questions.length) _questionIndex = 0;
});
print(_questionIndex);
print(questions.length);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My Flutter App'),
),
body: Column(
children: [
Question(questions[_questionIndex]),
Answer(_answerQuestion),
Answer(_answerQuestion),
Answer(_answerQuestion),
],
),
),
);
}
}
answer.dart
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function selectHandler;
Answer(this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text('Ans 1'),
onPressed: selectHandler,
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
),
);
}
}
Questions.dart
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
child: Text(
questionText,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}
Now I have tried to look at the logic, constructor is properly defined in the answer.dart file and it has been handeled well in the main.dart as well.
I am still learning and running out of options to solve this error.
can anyone please help to resolve this error.
Change it to this:
onPressed: ()=> selectHandler()

(FLUTTER) I'm getting this problem: throw UnimplementedError();

I have a total of 10 hours of coding experience so spare my ignorance. Under the TODO it's supposed to be (this is what the tutorial shows) return null; instead of throw UnimplementedError();
This is a copy of what I have.
void main() => runApp(MyQuizApp());
class MyQuizApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
throw UnimplementedError();
}
}
class MyQuizAppState extends State<MyQuizApp> {
var questionIndex = 0;
void answerQuestion() {
questionIndex = questionIndex + 1;
print(questionIndex);
}
#override
Widget build(BuildContext context) {
var questions = [
"What\'s your favorite color?",
"What\'s your favorite fruit?",
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Personality Quiz"),
),
body: Column(
children: [
Text(questions[questionIndex]),
RaisedButton(
child: Text("Answer 1"),
onPressed: answerQuestion,
),
RaisedButton(
child: Text("Answer 2"),
onPressed: () => print("Answer chosen!"),
),
RaisedButton(
child: Text("Answer 3"),
onPressed: () {
print("Answer chosen!");
},
),
],
),
),
);
}
}
This should fix it!
class MyQuizApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
_MyQuizAppState createState() => _MyQuizAppState();
}
}

Error with displaying message after quiz ends , flutter

Image
There are 3 questions in my app currently and as per my code after all my questions are answered one by one, a widget should appear on the screen which completely fills the screen and which should say " You did it". But unfortunately, I have been trying a lot and still can't find solution.
below is code for main.dart
import 'package:flutter/material.dart';
import './quiz.dart';
import './result.dart';
//void main(){
//runApp(MyApp());
//}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final _questions = const [
{
'questionText': 'What\'s is your favourite color? ',
'answers': ['Black', 'Red', 'Green', 'white'],
},
{
'questionText': 'What\'s is your favourite animal?',
'answers': ['Snake', 'Elephant', 'Lion'],
},
{
'questionText': 'Who is your favourite instructor? ',
'answers': ['Max', 'Max', 'Max', 'Max'],
},
];
var _questionIndex = 0;
void _answerQuestion() {
// var aBool= true;
// aBool = false;
setState(() {
_questionIndex = _questionIndex;
});
print(_questionIndex);
if (_questionIndex < _questions.length) {
print('We have more questions!');
} else {
print('No more questions!');
}
}
#override
Widget build(BuildContext context) {
// var dummy = ['Hello'];
// dummy.add('Max');
// print(dummy);
// dummy = [];
// questions = [];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body : _questionIndex <= 2
? Quiz(
answerQuestion: _answerQuestion,
questionIndex: _questionIndex,
questions: _questions,
)
: Result(),
),
);
}
}
below is code for question.dart
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: Text(
questionText,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}`
below id code for answer.dart
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function selectHandler;
final String answerText;
Answer(this.selectHandler, this.answerText);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text(answerText),
onPressed: selectHandler,
),
);
}
}
below is code for quiz.dart
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final List<Map<String, Object>>questions;
final int questionIndex;
final Function answerQuestion;
Quiz({
#required this.questions,
#required this.answerQuestion,
#required this.questionIndex,
});
Widget build(BuildContext context) {
return Column(
children: [
Question(
questions[questionIndex]['questionText'],
),
...(questions[questionIndex]['answers'] as List<String>)
.map((answer) {
return Answer(answerQuestion, answer);
}).toList()
],
);
}
}
below is code for result.dart
import 'package:flutter/material.dart';
class Result extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Text('You did it!'),
);
}
}
The moment I fixed the following line, your app started working as you described. Going through each question and then showing the "You did it!" text.
setState(() {
_questionIndex++;
});
You were just doing _questionIndex = _questionIndex before, which doesn't change any value.
I am not getting the error you mentioned,
Here what I did,
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _questions = const [
{
'questionText': 'What\'s is your favourite color? ',
'answers': ['Black', 'Red', 'Green', 'white'],
},
{
'questionText': 'What\'s is your favourite animal?',
'answers': ['Snake', 'Elephant', 'Lion'],
},
{
'questionText': 'Who is your favourite instructor? ',
'answers': ['Max', 'Max', 'Max', 'Max'],
},
];
var _questionIndex = 0;
void _answerQuestion(String question, String selectedAnswer) {
print("==============================================");
print("QUESTION: $question");
print("SELECTED ANSWER: $selectedAnswer");
print("==============================================");
setState(() {
_questionIndex++;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: _questionIndex < _questions.length //TODO:
? Quiz(
quizQuestion: _questions[_questionIndex]["questionText"],
quizOptions: _questions[_questionIndex]["answers"],
onAnswerSelect: _answerQuestion,
)
: Result(),
),
);
}
}
class Quiz extends StatelessWidget {
final String quizQuestion;
final List<String> quizOptions;
final void Function(String, String) onAnswerSelect;
Quiz({
#required this.quizQuestion,
#required this.quizOptions,
#required this.onAnswerSelect,
});
Widget build(BuildContext context) {
return Column(
children: [
Question(quizQuestion),
...quizOptions.map(
(option) => Answer(
answerText: option,
selectHandler: () => onAnswerSelect(quizQuestion, option),
),
),
],
);
}
}
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: Text(
questionText,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}
class Answer extends StatelessWidget {
final String answerText;
final VoidCallback selectHandler;
Answer({this.answerText, this.selectHandler});
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text(answerText),
onPressed: selectHandler,
),
);
}
}
class Result extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Text('You did it!'),
);
}
}