Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

enter image description here

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() {
       //....
    }
})
like image 252
GensaGames Avatar asked Nov 16 '19 19:11

GensaGames


Video Answer


2 Answers

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.

like image 176
Miki Avatar answered Sep 19 '22 17:09

Miki


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.

like image 23
Rémi Rousselet Avatar answered Sep 17 '22 17:09

Rémi Rousselet