简体   繁体   中英

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

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.

This is an alternative way, but not fully equivalent:

Problem, eg: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM