Hardik
Hardik

Reputation: 424

How to Create Dot Function in Dart or Flutter

Suppose I want to convert a UNIX integer into DateTime Format when called upon. (That's just an example) I want to create a function just like .toUpperCase(); , .toString(); where function takes that particular item as argument without writing inside brackets. I did try going inside these default core functions but didn't help.

How do I do that for custom functions? right now I'm here:

//------------- main()----------//

void main() {
  int unixDT = 1619691181;
// print(unixDT.toDateString()); //<-----this is what I'm looking for

}

//------- This is a function that should be in another-separate dart file-------//

String toDateString(int dt) {
  DateTime datetime = new DateTime.fromMillisecondsSinceEpoch(dt);
  return datetime.toString();
}

If you need clarification, please comment down. This is my very first question on StackOverflow so I apologize for mistakes if any.

Upvotes: 2

Views: 498

Answers (4)

Vadim Popov
Vadim Popov

Reputation: 772

You should use extension methods

Example:

extension ExtendedDynamic on dynamic {
 double toDouble() {
   final sValue = this?.toString() ?? '';
   final double parsedValue = double?.tryParse(sValue) ?? 0.0;
   return parsedValue;
 }
}

void someMethod() {
  final dynamic test = 0.0;
  print(test.toDouble());
}

In your case it will be like this:

extension ExtendedInt on int {
 String toDateString() {
  final dateString = 'your code...';
  return dateString;
 }
}

void someMethod() {
 int unixDT = 1619691181;
 print(unixDT.toDateString());
}

Important thing : Wherever you want to use this extension, you must import it

import 'package:yourProject/extensions/int_extention.dart';

Upvotes: 0

sagar shah
sagar shah

Reputation: 11

You can try to use this to refer to same object that is calling that method, Hope that will help

Upvotes: 0

Ahmet KAYGISIZ
Ahmet KAYGISIZ

Reputation: 202

You can use extension methods for this situations. You can add a method in Integer. For more details https://dart.dev/guides/language/extension-methods

Upvotes: 1

julemand101
julemand101

Reputation: 31269

Sounds like you are looking for extension methods:

void main() {
  const unixDT = 1619691181;
  print(unixDT.toDateString()); // 1970-01-19 18:54:51.181
}

extension IntToDateStringExtension on int {
  String toDateString() => DateTime.fromMillisecondsSinceEpoch(this).toString();
}

Upvotes: 4

Related Questions