Flutter, Dart. Create Anonymous Class

Flutter, Dart. Create Anonymous Class

Maybe it's really dumb question. But I cannot believe there is no resources, where it's described. Even from the official documentation. What I'm trying to do, it's create Anonymous class for the next function.

How to create Anonymous class in Dart with custom function something like next in Kotlin?

Handler(Looper.getMainLooper()).post(Runnable() {
    @override
    open fun run() {
        //...
    }

    private fun local() {
       //....
    }
})

2 Answers

Dart does not support creating an anonymous class.

What you're trying to do is not possible.

On the other hand, you can create anonymous functions. So you could use that to mimic an anonymous class.

The idea is to add a constructor of your abstract class, that defer its implementation to callbacks.

abstract class Event {
  void run();
}

class _AnonymousEvent implements Event {
  _AnonymousEvent({void run()}): _run = run;

  final void Function() _run;

  @override
  void run() => _run();
}

Event createAnonymousEvent() {
  return _AnonymousEvent(
    run: () => print('run'),
  );
}

It's not strictly the same as an anonymous class and is closer to the decorator pattern. But it should cover most use-cases.

4

This is an alternative way, but not fully equivalent:

Problem, e.g.: I would like to implement OnChildClickListener inline in my code without class. For this method:

void setOnChildClickListener(OnChildClickListener listener) {
    ...
}

Instead of this:

abstract class OnChildClickListener {
  bool onChildClick(int groupPosition, int childPosition);
}

use this:

typedef OnChildClickListener = Function(int groupPosition, int childPosition);

And in code you can implement it in this way:

listView.setOnChildClickListener((int groupPosition, int childPosition) {
  // your code here
});

In other words do not use abstract class, but use typedef.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.