[英]Got this error while passing callback function in flutter, Can anyone solve this
在這里,我正在嘗試制作一個 Begginer 測驗應用程序。 嘗試為每個小部件創建一個單獨的文件。 在此過程中,使用回調 function 出現錯誤,無法找到解決方法。
'''
import 'package:flutter/material.dart';
import 'question.dart';
import 'answer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> 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 = [
'What\'s your choice of color ?',
'What\'s your choice of animal'
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: (Text('Quiz time')),
),
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('Answer 1'),
onPressed:selectHandler,
**here in selectHandler it is showing error**
),
);
}
}
''' 參數類型'Function' 不能分配給參數類型'void Function()?'。
將您的 selectHandler 類型更新為VoidCallback
應該沒問題
final VoidCallback selectHandler;
注意:它是this的副本 你需要調用這樣的函數;
final void Function() selectHandler; // instead of final Function selectHandler;
或者你也可以在下面使用。 這兩種解決方案是相同的;
final VoidCallback selectHandler;
答案很簡單,您必須在Answer.dart文件中更新這一行。
final Function selectHandler;
將此行替換為
final VoidCallback selectHandler;
這條線將解決您的問題。
如果 'final Function selectHandler' 則使用 'final VoidCallback selectHandler'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.