Flutter Functions on Button Click

Added: In the previous post “Flutter Column Layout Widget” we created a Column() layout widget that took ‘children’ argument which was a list of Widgets, one Text() widget and three ElevatedButton() widgets.

ElevatedButton() widget took two arguments.

  1. child which takes a Text() widget i.e, text of the button.
  2. onPressed which we passed null at that time.

Here is the snapshot of that code snipped.

body: Column(
          children: <Widget>[
            Text('The question'),
            ElevatedButton(child: Text('Answer1'), onPressed: null,),
            ElevatedButton(child: Text('Answer2'), onPressed: null,),
            ElevatedButton(child: Text('Answer3'), onPressed: null,),
          ], //<Widget>[]
        ), //Column()

Since we were passing null to onPressed, all three buttons were disabled and we can’t click/tap these.

Now we’ll create a function (answerQuestion) in MyApp class that will be passed to ElevatedButton() onPressed argument. In that function we’ll just print some text on the console.

 

//File Name: main.dart
import 'package:flutter/material.dart';

/*
* The arrow function allows us to create a simplified function consisting of a single expression.
* We can omit the curly brackets and the return keyword
*/

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  void answerQuestion(){
    print('Answer chosen!');
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      /*
      * A Scaffold Widget provides a framework which implements the basic material design visual
      * layout structure of the flutter app.
       */
      home: Scaffold(
        appBar: AppBar(
          title: Text('First Flutter App'),
        ),
        body: Column(
          children: <Widget>[
            Text('The question'),
            ElevatedButton(
              child: Text('Answer1'),
              //onPressed takes a function
              onPressed: answerQuestion,
            ),
            ElevatedButton(
              child: Text('Answer2'),
              onPressed: answerQuestion,
            ),
            ElevatedButton(
              child: Text('Answer3'),
              onPressed: answerQuestion,
            ),
          ],
        ),
      ),
    );
  } //build()
} //MyApp()

Output: The buttons are enabled now and we can tap them and when we tap a button we’ll see ‘Answer chosen!’ text in console.

Output: Connect Functions with Button Click
Console Output

This was a simple addition of a function answerQuestion() in MyApp class and we passed that function to the ElevatedButton() onPressed argument.

Happy Coding!

Comments

comments

no responses for Flutter Functions on Button Click

    Leave a Reply

    Your email address will not be published. Required fields are marked *