Flutter/Dart Anonymous Function

Anonymous function is called anonymous because it has no name. Anonymous function is always a good idea if you never need to call it from anywhere else, it has no name and you can’t call it from anywhere else.

//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: () => print('Answer2 chosen!'),
            ),
            ElevatedButton(
              child: Text('Answer3'),
              onPressed: () {
                //...multiline function body
                print('Answer3 chosen');
              },
            ),
          ],
        ),
      ),
    );
  } //build()
} //MyApp()

Output

Output
Console Output

Happy Coding!

Comments

comments

one response for Flutter/Dart Anonymous Function

  1. […] from our last blog post “Flutter/Dart Anonymous Function” , in this post we have added a list of questions in build() for now, with only two […]

  2. Leave a Reply

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