A lot of flutter widgets accept actions when a user interacts with a widget such as a raised button which has a onPressed argument.

onPressed arguments accept a function definition or a pointer towards a function that is responsible for the action when the user presses the button.

we can do this by defining a function or using an anonymous function as shown below:

 

if you are going to define a function make sure it's in the same class that you working on, for e.g in the app below my defined function is called answerQuestion and is defined in MyApp, and it's used in MyApp as well, this is just good practice and it keeps your class methods neat and tidy.

 

you can use anonymous functions with the arrow => syntax when you have one expression or curly bracket syntax {} when you have more than one expression in your function.

 

 

 

import 'package:flutter/material.dart';

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

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

class MyApp extends StatelessWidget {
  
  void answerQuestion() {
    print("Answered Question!");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My Title'),
        ),
        body: Column(
          children: [
            Text('What is your name?'),
            RaisedButton(
              child: Text('Answer 1'),
              onPressed: answerQuestion, // defined function, function is defined above in the same class as a method!!
            ),
            RaisedButton(
              child: Text('Answer 2'),
              onPressed: () => print("Answer 2 was chosen!"),// anonymous function with just one expression!
            ),
            RaisedButton(
              child: Text('Answer 3'),
              onPressed: (){
                print("blah blah");
                print("Answer 2 was chosen!")
              },// Anonymous function with more than one expression
            ),
          ],
        ),
      ),
    );
  }
}