How to implement the ActionListener widget in Flutter?

· 5 min read
How to implement the ActionListener widget in Flutter?

ActionListener is the helper widget. You can use it to remove listeners from the action. So, in this article, we will see how to implement the ActionListener widget in Flutter.

How to implement the ActionListener widget in Flutter?

Listeners on the Action class must have their listener callbacks removed with Action.removeActionListener when the listener is disposed of. This widget helps with that. It provides a lifetime for the connection between the listener and the Action. It also helps by handling the adding and removing of the listener at the right points in the widget lifecycle.

If you listen to an Action widget in a widget hierarchy, you should use this widget. If you are using an Action outside of a widget context, then you must call removeListener yourself.

Properties:

  • action: The Action that the callback will be registered with.
  • child: This widget can only have one child. To layout multiple children, let this widget’s child be a widget such as Row, Column, or Stack, which have a children property, and then provide the children to that widget.
  • hashCode: The hash code for this object.
  • key: Controls how one widget replaces another widget in the tree.
  • listener: The ActionListenerCallback callback to register with the action.
  • runtimeType: A representation of the runtime type of the object.

Example:

import 'package:flutter/material.dart';

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

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

class ActionListenerExample extends StatefulWidget {
  const ActionListenerExample({Key? key}) : super(key: key);

  @override
  State<ActionListenerExample> createState() => _ActionListenerExampleState();
}

class _ActionListenerExampleState extends State<ActionListenerExample> {
  bool _on = false;
  late final MyAction _myAction;

  @override
  void initState() {
    super.initState();
    _myAction = MyAction();
  }

  void _toggleState() {
    setState(() {
      _on = !_on;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: OutlinedButton(
            onPressed: _toggleState,
            child: Text(_on ? 'Disable' : 'Enable'),
          ),
        ),
        if (_on)
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: ActionListener(
              listener: (Action<Intent> action) {
                if (action.intentType == MyIntent) {
                  ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                    content: Text('Action Listener Called'),
                  ));
                }
              },
              action: _myAction,
              child: ElevatedButton(
                onPressed: () => const ActionDispatcher()
                  .invokeAction(_myAction, const MyIntent()),
                child: const Text('Call Action Listener'),
              ),
            ),
          ),
        if (!_on) Container(),
      ],
    );
  }
}

class MyAction extends Action<MyIntent> {
  @override
  void addActionListener(ActionListenerCallback listener) {
    super.addActionListener(listener);
    print('Action Listener was added');
  }

  @override
  void removeActionListener(ActionListenerCallback listener) {
    super.removeActionListener(listener);
    print('Action Listener was removed');
  }

  @override
  void invoke(covariant MyIntent intent) {
    notifyActionListeners();
  }
}

class MyIntent extends Intent {
  const MyIntent();
}

/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return const ActionListenerExample();
  }
}

Output:

ActionListener Class

Conclusion:

Thanks for being with us on a Flutter Journey!

So, in this article, we have seen how to implement the ActionListener widget in Flutter.  Also, feel free to comment and provide any other suggestions regarding Flutter.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. Also, the portal is full of cool resources from Flutter like Flutter Widget GuideFlutter Projects, Code libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply