【问题标题】:how to pass function to other class and return response of function to main class in flutter如何将函数传递给其他类并将函数的响应返回给flutter中的主类
【发布时间】:2019-12-18 05:40:57
【问题描述】:

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

【问题讨论】:

    标签: function class flutter dart arguments


    【解决方案1】:

    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,
                ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-27
      • 2021-02-21
      • 2014-07-25
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多