GensaGames
GensaGames

Reputation: 5788

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() {
       //....
    }
})

Upvotes: 19

Views: 13429

Answers (3)

atreeon
atreeon

Reputation: 24107

Dart 3 has record types which are similar to anonymous classes in c#.

  var record0 = ('String', 5);
  print(record0);

Has in built getters; either positional or named:

  var record = ('first', a: 2, b: true, 'last');
  print("${record.a}, ${record.$1}");

Record types use duck typing for equality.

Upvotes: 0

Miki
Miki

Reputation: 450

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.

Upvotes: 3

Rémi Rousselet
Rémi Rousselet

Reputation: 277067

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.

Upvotes: 16

Related Questions