by @kodeazy

what is the difference between named funtion and anonymous function with an example widget in dart file?

Home » flutter » what is the difference between named funtion and anonymous function with an example widget in dart file?
  • A function is a reusable part of a program.
  • In this tutorial we will be discussing about anonymous and normal functions in flutter.
  • A normal function is a function which has name where as anonymous function does not have.
  • Below is an example of creating a button and executing a normal function after clicking the button with out using anonymous function.

    import 'package:flutter/material.dart';
    void main() {
    runApp(MyApp1());
    }
    class MyApp1 extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Normal function Example'),
        ),
        body: RaisedButton(
            child: Text("Normal Function"), onPressed: normalFunctionExample),
      ),
    );
    }
    }
    normalFunctionExample() {
    print('Normal function executed');
    }

    Output: Normal Function example Image

  • Anonymous function is a function which has no name.
  • Below is an example of creating a button and executing a function after clicking the button using anonymous function
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp1());
}
class MyApp1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Anonymous function Example'),
        ),
        body: Column(
          children: <Widget>[
            RaisedButton(
                child: Text("Anonymous function using Arrow function"),
                onPressed: () =>
                    print("welome to kodeazy.com using Arrow functions")),
            RaisedButton(
                child: Text("Anonymous function with out using Arrow function"),
                onPressed: () {
                  print("welome to kodeazy.com without using arrow functions");
                }),
          ],
        ),
      ),
    );
  }
}

Output:

Anonymous Function example Image