Skip to content

Instantly share code, notes, and snippets.

@AngDrew
Last active April 16, 2024 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AngDrew/2bcb2867c926562af07aecf6cb0c5116 to your computer and use it in GitHub Desktop.
Save AngDrew/2bcb2867c926562af07aecf6cb0c5116 to your computer and use it in GitHub Desktop.
flutter extensions
extension AutoCompleteOnList<T> on List<T> {
List<String> autoCompleteOnList(String query) {
return where((T element) {
String option = element.toString();
return option.toLowerCase().contains(query.toLowerCase());
}).map((T e) => e.toString()).toList();
}
}
import 'package:flutter/material.dart';
import 'package:super_app/app.dart';
import 'package:super_app/core/core.dart';
extension ThemeExtensionGetter on BuildContext {
/// Usage example: `context.colors`
AppColorThemeExt get colors =>
Theme.of(this).extension<AppColorThemeExt>() ??
lightThemeExtension.firstWhere((ThemeExtension<dynamic> element) =>
element.type == AppColorThemeExt) as AppColorThemeExt;
/// Usage example: `context.styles`
AppStyleThemeExt get styles =>
Theme.of(this).extension<AppStyleThemeExt>() ??
lightThemeExtension.firstWhere((ThemeExtension<dynamic> element) =>
element.type == AppStyleThemeExt) as AppStyleThemeExt;
}
import 'package:components/components.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:super_app/core/core.dart';
extension CopyOnTextTapped on Text {
Widget copyToClipboardOnTapped(BuildContext context) {
return GestureDetector(
onTap: () {
data?.let((String self) {
Clipboard.setData(ClipboardData(text: self));
print('Copied to clipboard: $self');
ToastHelper.success('Copied to clipboard');
});
},
child: Material(
color: Colors.transparent,
child: this,
),
);
}
}
import 'package:intl/intl.dart';
extension DateTimeExtension on DateTime {
/// dd MMM yyyy
String get toReadableDate =>
DateFormat('dd MMM yyyy', 'en_US').format(this).toString();
/// HH:mm:ss
String get toTime => DateFormat('HH:mm:ss', 'en_US').format(this).toString();
/// HH:mm
String get toTimeShort =>
DateFormat('HH:mm', 'en_US').format(this).toString();
/// yyyyMMdd
String get toApiFormat =>
DateFormat('yyyyMMdd', 'en_US').format(this).toString();
/// dd
String get toDay => DateFormat('dd', 'en_US').format(this).toString();
/// MMM
String get toMonthName => DateFormat('MMM', 'en_US').format(this).toString();
/// MMM
String get toMonth => DateFormat('MM', 'en_US').format(this).toString();
/// yyyy
String get toYear => DateFormat('yyyy', 'en_US').format(this).toString();
/// 1 Day / xx Days
String getReadableDuration(DateTime? other) {
Duration? duration = other?.difference(this);
int? days = duration?.inDays ?? 0;
if (days == 1) {
return '1 Day';
}
return '${NumberFormat().format(days)} Days';
}
}
import 'package:dio/dio.dart';
import 'package:super_app/core/core.dart';
extension HelperDioException on DioException {
String? get getErrorMessage {
ErrorResponse errorResponse = ErrorResponse.fromJson(response?.data);
String? joinnedErrors = errorResponse.error?.errorMessages?.join('\n\n');
return joinnedErrors;
}
}
extension HelperOnList<T> on List<T> {
List<T> get unmodifiable => List<T>.unmodifiable(this);
List<T> get copy => List<T>.from(this);
}
export 'auto_complete_on_list.dart';
export 'context_extension.dart';
export 'copy_on_text_tapped.dart';
export 'date_time_extension.dart';
export 'dio_exception.dart';
export 'ext_on_list.dart';
export 'flexible_padding_extension.dart';
export 'inkwell_wrapper_on_widget.dart';
export 'nullable_bool_extension.dart';
export 'nullable_object_extension.dart';
export 'nullable_string_extension.dart';
export 'object_extension.dart';
export 'string_extension.dart';
export 'tooltip_on_text.dart';
export 'wait_frame_to_run_function.dart';
import 'package:flutter/widgets.dart';
enum LargePaddingType {
horizontal,
vertical,
all,
}
extension FlexiblePaddingExtension on Widget {
Widget withLargePadding({
LargePaddingType largePaddingType = LargePaddingType.all,
}) {
switch (largePaddingType) {
case LargePaddingType.horizontal:
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: this,
);
case LargePaddingType.vertical:
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: this,
);
case LargePaddingType.all:
default:
return Padding(
padding: const EdgeInsets.all(16.0),
child: this,
);
}
}
}
import 'package:components/components.dart';
import 'package:flutter/material.dart';
extension InkWellWrapperOnWidget on Widget {
Widget withInkWellWrapper({
required VoidCallback? onTap,
BorderRadius? borderRadius,
Color? splashColor,
Color? highlightColor,
Color? backgroundColor,
EdgeInsetsGeometry? padding,
ShapeBorder? shape,
Key? key,
}) {
return Material(
color: backgroundColor ?? Colors.transparent,
shape: shape ??
RoundedRectangleBorder(
borderRadius: borderRadius ?? MrtRoundedBorder.largeRound,
),
child: InkWell(
key: key,
onTap: onTap,
splashColor: splashColor,
highlightColor: highlightColor,
customBorder: shape ??
RoundedRectangleBorder(
borderRadius: borderRadius ?? MrtRoundedBorder.largeRound,
),
child: Padding(
padding: padding ?? const EdgeInsets.all(8.0),
child: this,
),
),
);
}
}
extension NullableBoolExtension on bool? {
bool get isTrue => this == true;
bool get isFalse => this == false;
}
extension NullableObjectExtension on Object? {
bool get notNull => this != null;
bool get isNull => this == null;
}
extension NullableStringExtension on String? {
bool get emptyOrNull {
return this == null &&
(this?.isEmpty == true || this?.trim().isEmpty == true);
}
bool get notEmptyOrNull {
return this != null &&
this?.isNotEmpty == true &&
this?.trim().isNotEmpty == true;
}
}
import 'dart:convert';
extension ObjectExtension on Object {
String toJson() {
return jsonEncode(this);
}
Object? fromJson() {
return jsonDecode(toString());
}
}
import 'dart:developer';
import 'package:intl/intl.dart';
import 'package:super_app/core/core.dart';
extension StringExtension on String {
/// format dd MMM yyyy to DateTime
DateTime? get toDateFromReadableFormat {
if (isEmpty) return null;
try {
return DateFormat('dd MMM yyyy', 'en_US').parse(this);
} catch (e) {
return null;
}
}
/// format dd/MM/yyyy to DateTime
DateTime? get toDateFromSlashedFormat {
if (isEmpty) return null;
try {
return DateFormat('dd/MM/yyyy', 'en_US').parse(this);
} catch (e) {
return null;
}
}
/// format DateTime to dd/MM/yyyy String
String? get toReadableFromSlashedFormat {
if (isEmpty) return null;
try {
return DateFormat('dd/MM/yyyy', 'en_US').parse(this).toReadableDate;
} catch (e) {
return null;
}
}
/// format dd MMM yyyy to DateTime
DateTime? get toDateFromApi {
if (isEmpty) return null;
try {
return DateFormat('dd MMM yy', 'en_US').parse(capitalize);
} catch (e) {
log(
e.toString(),
name: 'str.ext',
);
return null;
}
}
DateTime? get toDateTimeFromApi {
if (isEmpty) return null;
try {
return DateFormat('dd MMM yy HH:mm', 'en_US').parse(capitalize);
} catch (e) {
log(
e.toString(),
name: 'str.ext',
);
return null;
}
}
String ellipsize({int maxChar = 8}) =>
length > (maxChar + 2) ? '${substring(0, maxChar)}...' : this;
String get capitalize {
if (isEmpty) {
return this;
}
List<String> words = split(' ');
Iterable<String> capitalizedWords = words.map((String word) {
if (word.isEmpty) {
return word;
}
return word[0].toUpperCase() + word.substring(1).toLowerCase();
});
return capitalizedWords.join(' ');
}
bool nestedContains(List<String> values) {
if (isEmpty) {
return false;
}
for (String value in values) {
if (!contains(value)) {
return false;
}
}
return true;
}
}
import 'package:flutter/material.dart';
extension TooltipOnText on Text {
Widget withTooltip() {
return Tooltip(
message: data ?? '',
triggerMode: TooltipTriggerMode.tap,
enableFeedback: true,
child: this,
);
}
}
extension WaitFrameToRunFunction on Function() {
Future<void> waitFrameToRun() async {
Future<void>.microtask(() {
this.call();
});
}
}
extension WaitFrameToRunFunctionWithArg<T> on Function(T) {
Future<void> waitFrameToRun(T arg) async {
Future<void>.microtask(() {
this.call(arg);
});
}
}
extension WaitFrameToRunFunctionWithArg2<T, U> on Function(T, U) {
Future<void> waitFrameToRun(T arg1, U arg2) async {
Future<void>.microtask(() {
this.call(arg1, arg2);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment