Home > Mobile >  buttons can't be pressed with flutter
buttons can't be pressed with flutter

Time:10-25

I have a problem with the buttons I can't click on them... I just create a class answer that takes two parameters from the main

this how the buttons looks like

this is the answer class that took two parameters

 class Answer extends StatelessWidget {
  final String answerText;
  final Function x;

  const Answer(this.x, this.answerText);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: x(),
        child: Text(
          answerText,
          style: TextStyle(fontSize: 30),
        ),
      ),
    );
  }`

and this is the main class i just call the Answer class and i add to it the function answerquestion and string answer

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _i = 0;
  void answerquestion() {
    print("good ");
    print(_i);
  }

  var question = [
    "what's ur fav color?",
    "what's ur fav animal?",
    "what's ur fav food?"
  ];
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text("Quiz App"),
        ),
        body: Container(
          margin: EdgeInsets.all(10),
          width: double.infinity,
          child: Column(
            //crossAxisAlignment: CrossAxisAlignment.end,
            //  mainAxisAlignment: MainAxisAlignment.spaceBetween(1),
            children: <Widget>[
              Question(question[1]),
              Answer(answerquestion, "ans1"),
              Answer(answerquestion, 'ans2'),
            ],
          ),
        ),
      ),
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
    );
  }

CodePudding user response:

The problem is, you are executing the function on the widget creation. The correct sintax should be either

onPressed: () => x(),

or:

onPressed: x
  • Related