lib/answer.dart:16:20: Error: The argument type 'Function' can't be assigned to the parameter type 'void Function()?' - flutter

This is the main.dart file:
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
import 'package:path/path.dart';
void main() {
runApp(MyFirstApp());
}
class MyFirstApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyFirstAppState();
}
}
class _MyFirstAppState extends State<MyFirstApp> {
var _questionIndex = 0;
void _ansButtonPress(context) {
setState(() {
_questionIndex = _questionIndex + 1;
});
}
var questions = ['favorate color ', 'favorate animal', 'where is this'];
var answers = ['Option 1', 'Option 2', 'Option 3'];
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My first app '),
),
body: Column(
children: [
Question(
questions[_questionIndex],
),
Answer(_ansButtonPress),
Answer(_ansButtonPress),
Answer(_ansButtonPress),
],
),
),
);
}
}
This is answwers.dart file:
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function selectHandler;
Answer(this.selectHandler);
// const Answer({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.blue,
child: Text('Answer 1'),
onPressed: selectHandler,
),
);
}
}`enter code here`
[enter image description here][1]
This is questions.dart:
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function selectHandler;
Answer(this.selectHandler);
// const Answer({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.blue,
child: Text('Answer 1'),
onPressed: selectHandler,
),
);
}
}
I am working on a quiz app by watching a tutorial, I am just a beginner now facing an error. I can't fix it, I added the code and error with this.
lib/answer.dart:16:20: Error: The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.
'Function' is from 'dart:core'.
onPressed: selectHandler,

The onPressed property of the button in question is a VoidCallback?, so for ease of use, make your property a VoidCallback (nullable or not is up to you), too:
final Function selectHandler;
becomes
final VoidCallback selectHandler;
Then make sure the method you pass to this property actually is of this signature:
void _ansButtonPress(context) {
becomes
void _ansButtonPress() {
I don't know what that "context" was supposed to do anyway, it wasn't used.
Now it should work.

Use
final void Function() selectHandler;
instead of
final VoidCallback? selectHandler;
and
final Function selectHandler;

Related

I have issue's when i will using Function callback

i have custom button widget from different file, then i create callback function it might will showing pointer from main function, when i'm running i have issues this:
Issues
and this code, main layout:
import 'package:flutter/material.dart';
import './increment.dart';
void main() => runApp(MaterialApp(
home: HomePage(),
));
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _counter = 0;
void increment() {
setState(() {
_counter = _counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Text('Result = ${_counter}'),
SizedBox(
height: 100,
),
Inc(increment)
// ElevatedButton(onPressed: increment, child: Text('-'))
],
),
),
);
}
}
and this widget custom:
import 'package:flutter/material.dart';
class Inc extends StatelessWidget {
final Function selectInc;
Inc(this.selectInc);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
height: 100,
child: ElevatedButton(onPressed: selectInc(), child: Text('+')),
);
}
}
how i can solve this?
onPressed: selectInc()
This is calling the function and using the result. You need to use the function only as a parameter:
onPressed: () => selectInc()
Since your selectInc method is a void function, the exact type the callback requires, you could also omit the anonymous function wrapper and pass your callback directly:
onPressed: selectInc
However, it seems you need some more type safety for the compiler to not complain. Make
final Function selectInc;
look like this:
final VoidCallback selectInc;

Argument type 'Function' can't be assigned to the parameter type 'void'

I am passing a call back function from my child file to the parent file, in the elevated button class, I am passing the function in the class (in the child file )to the named parameter on pressed, but I am getting the error in the question above, while it worked for the tutorial I am using(academind).
How do I solve this?
CHILD file
class Answer extends StatelessWidget {
final Function selectHandler;
Answer(this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text('Answer 1'),
style: ElevatedButton.styleFrom(
primary: Colors.lightGreen
),
onPressed: selectHandler,
),
);
}
}
PARENT file
// ignore_for_file: prefer_const_constructors, avoid_print, prefer_const_literals_to_create_immutables, must_be_immutable, prefer_const_constructors_in_immutables
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() {
// ignore: todo
// TODO: implement createState
return _MyAppState();
}
}
class _MyAppState extends State <MyApp>{
var _questionsIndex = 0;
var questions = [
'What\'s your favourite book',
'What\'s your favourite colour',
'What\'s our favourite poem',
];
void _answerQuestion() {
setState(() {
_questionsIndex = _questionsIndex + 1;
if (_questionsIndex >= questions.length) _questionsIndex = 0;
});
print(_questionsIndex);
print(questions.length);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('My First App'),),
body: Column(
children: [
Question(
questions[_questionsIndex],
),
Answer(_answerQuestion),
Answer(_answerQuestion),
Answer(_answerQuestion),
],
)
),
);
}
}
Change Function to
void Function functionName(){}
or
VoidCallback functionName(){}
Same issue i have faced after updating this it is working
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final VoidCallback clickFunction;
const Answer(this.clickFunction,{Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(5),
child: RaisedButton(
padding: const EdgeInsets.all(10),
color: Colors.blue,
onPressed: clickFunction,
child: const Text("This is texxt"),
));
}
}
this is worked for me
final void Function()? FunctionName;

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()

Error: The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.'Function' is from 'dart:core'.onPressed: selectHandler

main.dart
import 'package:flutter/material.dart';
import './questions.dart';
import './answer.dart';
void main() {
runApp(AskMe());
}
class AskMe extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _AskMeState();
}
}
class _AskMeState extends State<AskMe> {
var _next_ques = 0;
void _Response() {
setState(() {
_next_ques += 1;
});
print(_next_ques);
}
#override
Widget build(BuildContext context) {
var questions = ["What is your Name ?", "What is your favourite color ?"];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Ask Me"),
),
body: Column(
children: [
Questions(questions[_next_ques]),
Answer(_Response),
Answer(_Response),
Answer(_Response),
],
),
),
);
}
}
questions.dart
import 'package:flutter/material.dart';
class Questions extends StatelessWidget {
final String questions;
Questions(this.questions);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(20),
child: Text(
questions,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}
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,
margin: EdgeInsets.all(10),
child: RaisedButton(
color: Colors.blueGrey,
child: Text("Question 1"),
onPressed: selectHandler,
),
);
}
}
The above code is for basic app that consists of 3 buttons for the questions shown as textview and clicking on button will display next question. The issue i'm facing is while making custom dart function in answer.dart i'm not able to call the pointer to the function _Response which is present in main.dart as it gives the error mentioned in the title. Thanks for the help.
Define function type like this:
class Answer extends StatelessWidget {
final Function() selectHandler;
...

Instantiate child button with given value, but it is not changed

I am learning new Dart/Flutter and try to make my own exercise. I believe I am missing something fundamental here.
Problem:
My button is showing question mark. But I instantiate it with value already
Question:
How to instantiate button with given text?
import 'package:complete_guide/question.dart';
import 'package:flutter/material.dart';
import 'answer.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int index = 0;
List<String> questions = [
"How may I help you?",
"What is you favorite dog?"
];
void _answerQuestion(){
setState(() {
index = index + 1;
});
print(index);
}
void showText(inputText){
print(inputText);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Stay Strong")
),
body: Center(
child: Column(
children: [
Question(questions[index]),
Answer("iddqd", _answerQuestion),
Answer("idkfa", _answerQuestion),
Answer("show me the money", _answerQuestion),
],
),
),
)
);
}
}
class Answer extends StatelessWidget {
final Function selectHandler;
String answerText = "?";
Answer(answerText, this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(answerText),
onPressed: selectHandler,
)
);
}
}
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(
this.questionText,
style: TextStyle(fontSize: 20, color: Colors.orange),
textAlign: TextAlign.center,
),
);
}
}
Please do not ignore analyzer warnings. They are there for a reason.
First, answerText should be marked as final. It should not be initialized so that it can be assigned a value in the constructor. Finally, you need to use the this. syntax that you've used for all of your other constructor parameters.
There is also no need of providing a default value of '?' for answerText because the constructor uses it as a required parameter, so that default value will never be used.
class Answer extends StatelessWidget {
final Function selectHandler;
final String answerText;
Answer(this.answerText, this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(answerText),
onPressed: selectHandler,
)
);
}
}