how to pass function to other class and return response of function to main class in flutter

305

Do

class subclassName
final function NameOfFunction;

subclassName(this.NameOfFunction);

in main class

subclassName(the function you want to pass);

main

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

sub class

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,
            ),
    );
  }
}
Share:
305
Admin
Author by

Admin

Updated on December 13, 2022

Comments

  • Admin
    Admin over 1 year

    i have a class that call it in main class but i want pass a function to sub class and run function to sub class and return response of function to main class how to do in flutter dart.