我在提升的按钮类中从我的子文件向父文件传递一个回调函数,我在类中(在子文件中)传递函数给按下时命名的参数,但是我得到了上面问题中的错误,而它在我使用的教程(academind)中是有效的。我该如何解决这个问题?
子文件
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,
),
);
}
}
父文件
// 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),
],
)
),
);
}
}
3条答案
按热度按时间z31licg01#
将
Function
更改为或
cwdobuhd2#
同样的问题,我已经面临更新后,这是工作
k10s72fa3#
这对我很有效