gpt4 book ai didi

function - 如何将函数传递给其他类并将函数的响应返回给 flutter 中的主类

转载 作者:IT王子 更新时间:2023-10-29 07:02:06 26 4
gpt4 key购买 nike

我有一个在主类中调用它的类,但我想将一个函数传递给子类并将函数运行到子类并将函数的响应返回给主类在 flutter dart 中如何做。

最佳答案

class subclassName
final function NameOfFunction;

subclassName(this.NameOfFunction);

在主类中

subclassName(the function you want to pass);

主要

class _MyAppState extends State<MyApp> {
var _questionIndex = 0;

void _answerQuestion() {
setState(() {
_questionIndex = _questionIndex + 1;
});
print(_questionIndex);
}

@override
Widget build(BuildContext context) {
print("object");
var questions = [
{
'questionText':'What\'s your favorite color?',
'answers': ['Black','Red','Green','White'],
},
{
'questionText':'What\'s your favorite animal?',
'answers': ['Rabbit','Snak','Elephant','Lion'],
},
{
'questionText':'who\'s your favorite instructor?',
'answers': ['suhaib','max','khalid','moh'],
}

];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(
questions[_questionIndex]['questionText'],
),
...(questions[_questionIndex]['answers'] as List<String>).map((answer){
return Answer(_answerQuestion, answer);
}).toList(),
],
),
),
);
}
}

子类

class Answer extends StatelessWidget {
final String textanswer;
final Function answerQuestion;
Answer(this.answerQuestion,this.textanswer);

@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text(textanswer),
onPressed: answerQuestion,
),
);
}
}

关于function - 如何将函数传递给其他类并将函数的响应返回给 flutter 中的主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com