Miscellaneous
A library that brings together a harmonious blend of essential tools, utilities, and components designed to supercharge my Dart projects.
put this in your pubspec.yaml
dependencies:
dart_fusion:
git:
url: https://github.com/Nialixus/dart_fusion.git
path: dart_fusion
ref: v3.1.7
# or import this one instead for flutter project
dart_fusion_flutter:
git:
url: https://github.com/Nialixus/dart_fusion.git
path: dart_fusion_flutter
ref: v3.1.7
also run this command in terminal
dart pub global activate --source git https://github.com/Nialixus/dart_fusion.git
The Dart Fusion CLI is a command-line tool that provides a set of utilities to simplifies common tasks such as asset generation, model updates, and localization.
[!NOTE] This also can be achieved using DRunner
Asset Generation : Easily generate asset classes from asset directories, making it simple to access assets in your Dart project. To scan asset files and generate them into one dart class, run this command
dart run dart_fusion asset
And this is the list of available commands.
OPTION | DESCRIPTION |
---|---|
-i, --input | Input directory of where assets took place. |
default to assets | |
-o, --output | Output file of generated asset class. |
default to lib/src/assets.dart | |
-h, --help | Print this usage information. |
Model Updates : Update models by generating toJSON, fromJSON and copyWith based on given annotation. To update these models, run this command
dart run dart_fusion model
And this is the available commands.
OPTION | DESCRIPTION |
---|---|
-i, --input | Input directory of the models. |
default to "" | |
-h, --help | Print this usage information. |
Localization : Generate localization classes from JSON files, simplifying the process of managing free translations in your Dart applications.
dart run dart_fusion localize
List of the commands
OPTION | DESCRIPTION |
---|---|
-i, --input | Input directory of where the JSON base translation took place. |
default to assets/translation/en.json | |
-o, --output | Generating JSON to easy_localization model |
--from | Base language used for translation |
default to en | |
--to | Targeted translation languages |
default to ["af","sq","am","ar","hy","as","ay","az","bm","eu","be","bn","bho","bs","bg","ca","ceb","zh-CN","zh","zh-TW","co","hr","cs","da","dv","doi","nl","en","eo","et","ee","fil","fi","fr","fy","gl","ka","de","el","gn","gu","ht","ha","haw","he","hi","hmn","hu","is","ig","ilo","id","ga","it","ja","jv","kn","kk","km","rw","gom","ko","kri","ku","ckb","ky","lo","la","lv","ln","lt","lg","lb","mk","mai","mg","ms","ml","mt","mi","mr","mni-Mtei","lus","mn","my","ne","no","ny","or","om","ps","fa","pl","pt","pa","qu","ro","ru","sm","sa","gd","nso","sr","st","sn","sd","si","sk","sl","so","es","su","sw","sv","tl","tg","ta","tt","te","th","ti","ts","tr","tk","ak","uk","ur","ug","uz","vi","cy","xh","yi","yo","zu"] | |
-h, --help | Print this usage information. |
D Annotations is a set of class used as an indicator for Dart Fusion CLI
model generation
fromJSON
, toJSON
and copyWith
inside the annotated class.
@model
class MyClass extends DModel {}
// or you can annotate it like this
@Model(immutable: true, copyWith: true, fromJSON: true, toJSON: true)
class MyClass extends DModel {}
Variable: Annotation of variable inside a model class with @Model
annotation.
@variable
final DModel value;
// or you can annotate it like this
@Variable(name: 'd_model', toJSON: true, fromJSON: true)
final DModel value;
And when you run
dart run dart_fusion model
This will resulting something like this
@model
class MyClass extends DModel {
const MyClass({required this.title, required this.value});
@Variable(name: 'd_model', toJSON: true, fromJSON: true)
final DModel value;
@variable
final String title;
@override
MyClass copyWith({DModel? value, String? title}) {
return MyClass(
value: value ?? this.value,
title: title ?? this.title,
);
}
@override
JSON get toJSON => {
'd_model': value.toJSON,
'title': title,
};
static MyClass fromJSON(JSON value){
return MyClass(
value: DModel.fromJSON(value.of<JSON>('d_model'),
title: value.of<String>('title'))
);
}
}
D Assertion is a set of assertion class used for performing assertions and validations.
Assert: The Assert
class facilitates assertion checks based on boolean conditions. If the assertion fails, it throws an Exception
with a provided message.
int number = 1;
Assert(
number.isEven, // conditional needed in assertion checker
'Number is not even!', // message if the conditional return false
);
Assert
class for handling response-related assertions.
return (context) {
final method = context.request.method;
Assert.response(
method == HttpMethod.post, // assertion checker
'Invalid Method!', // message if the conditional return false
statusCode: 405, // status code to send inside `ResponseException`
);
}
D Behavior is a custom scroll behavior for controlling the scrolling physics of scrollable widgets.
ScrollConfiguration(
behavior: DBehavior(
physics: BouncingScrollPhysics()),
child: ListView(),
);
D Builder is a widget that builds its child using a custom builder function with optional data.
DBuilder(
data: {"name": "John", "age": 30},
builder: (context, data) {
final name = data.of<String>("name");
final age = data.of<int>("age");
return Text("My name is $name and I am $age years old.");
},
)
D Exceptions is a set of exception class used in this library.
Type Exception: An exception caused by failing to parse Type
.
throw TypeException(
message: 'Type is not available',
);
Response
value.
throw ResponseException(
response: Response(
statusCode: 404,
)
);
An extension collection of mostly used function in flutter project.
Extension on numeric types (int, double) to add utility methods for limiting values within a specified range.
int min = 5.min(10);
print(min); // 10
double max = 100.0.max(10.0);
print(max); // 10.0
int number = 75.limit(0, 100);
print(number); // 75
Converts integer to a human-readable string representing bytes.
int bytes = 1048576;
String parse = bytes.toReadableBytes;
print(parse); // "1048.57 KB"
Extension on the Map<String, dynamic> value.
JSON
to another.
JSON json = {"primary": "1", "secondary": "2"};
JSON anotherJSON = {"primary": "10", "tertiary": "3"};
print(json.merge(anotherJSON)); // {"primary": "10", "secondary": "2", "tertiary": "3"}
dynamic
value in JSON
to given Object
with an optional onError
fallback.
JSON value = {"primary": "1"};
String primary = value.of<String>("primary");
print(primary); // "1"
String secondary = value.of<String>("secondary", "No Data");
print(secondary); // "No Data"
dynamic
value in JSON
to given nullable Object
.
JSON value = {"primary": "1"};
String? primary = value.maybeOf<String>("primary");
print(primary); // "1"
String? secondary = value.maybeOf<String>("secondary");
print(secondary); // null
A set of extension collection on BuildContext
.
Theme.of(context)
.
ThemeData theme = context.theme;
Theme.of(context).colorScheme
.
ColorScheme color = context.color;
Theme.of(context).textTheme
.
TextTheme text = context.text;
MediaQuery.of(context)
.
MediaQuery query = context.query;
MediaQuery.sizeOf(context)
.
Size suze = context.querySize;
MediaQuery.sizeOf(context).width
.
double width = context.width;
MediaQuery.sizeOf(context).height
.
double height = context.height;
400 px
or not.
bool isPhone = context.isPhone;
700 px
or not.
bool isDesktop = context.isDesktop;
400 px
and more than 700 px
or not.
bool isTablet = context.isTablet;
A set of extension collection on RequestContext
.
HttpMethod
out of RequestContext
.
HttpMethod method = context.method;
HttpMethod.get
or not.
bool isGET = context.isGET;
HttpMethod.post
or not.
bool isPOST = context.isPOST;
HttpMethod.put
or not.
bool isPUT = context.isPUT;
HttpMethod.delete
or not.
bool isDELETE = context.isDELETE;
bool isWS = context.isWebSocket;
RequestContext
.
JSON parameter = context.parameter;
RequestContext
.
JSON parameter = context.parameter;
JWT
Bearer Token.
JWT jwt = await context.verify((key) => Env.read<String>(key));
A set of extension collection on BuildContext
.
List<String> texts = ["one", "two", "three"];
List<Widget> widgets = texts.to((index, item) => Text("$index: $item"));
List<int> integers = [1, 2, 3];
List<int> sublist = integers.limit(1, 100);
print(sublist); // [2, 3]
Extending list of DModel
to get its toJSON values.
List<DModel> dmodels = [DModel(), DModel()];
List<JSON> jsons = dmodels.toJSON;
Capitalizing the first letter of String
s.
String word = 'magnificent'.capitalize;
print(word); // Magnificent
A widget for displaying vector or bitmap images from different sources.
// Vector / Bitmap image from file
DImage(source: File('path/to/images.svg'))
// Vector / Bitmap image from asset
DImage(source: 'assets/image/image.png');
// Vector / Bitmap image from Uint8List
DImage(source: Uint8List());
// Vector / Bitmap image from network
DImage(source: 'http://image.dom/asset.svg');
A simple logging utility for printing log messages with customizable log levels.
Exception e = Exception('something');
DLog(e); // Exception: something
A collection of DModel
models.
D Model: Base dart model which consist copyWith
, toJSON
, fromJSON
and toString
value.
class MyModel extends DModel {
@override
MyModel copyWith() {
return MyModel();
}
static MyModel fromJSON(JSON value) {
return MyModel();
}
@override
JSON get toJSON {
return {};
}
}
Response Model: Basic model in root of every Response
, containing success
status, message
and also data
that extends DModel
class.
ResponseModel(
success: true,
message: 'Successfully Fetching Data!',
data: const ResponseDataModel());
ResponseModel
to indicate the relationship of resources.
LinkModel(
method: HttpMethod.get,
description: 'Read User Detail',
reference: '/user/123');
A builder widget that displays an overlay.
final overlay = DOverlay(builder: (context, progress, controller) => YourWidget());
GestureDetector(
onTap: () {
overlay.controller.display(context);
}
);
A utility class for parsing mostly related to http request.
DELETE
, GET
, HEAD
, OPTIONS
, PATCH
, POST
or PUT
.
HttpMethod method = HttpMethod.get;
final message = DParse.httpMethodMessage(method.name);
print(message); // 'Data successfully loaded'
statusCode
value in [Response].
Response response = Response(...);
final message = DParse.httpStatusMessage(response.statusCode);
print(message); // 'Not Found: The requested resource could not be found'
FormatException exception = FormatException('Unexpected end of input (at character 1)');
final message = DParse.exceptionMessage(exception);
print(message); // 'Data is not exist'
Runner class for `Dart Fusion CLI'.
DModel
, like copyWith
, fromJSON
and toJSON
.Locale
and generate a model to be integrated with easy_localization
.Set this in your root main.dart
File:
main.dart
void main() { WidgetsFlutterBinding.ensureInitialized(); DartFusion.runner(const [AssetRunner(), ModelRunner(), LocalizeRunner()]); runApp(...); }
A set of service collection mosty used in dart backend.
Middleware for handling requests and responses in Dart Frog
. This middleware supports both regular HTTP requests and websockets.
File:
_middleware.dart
Handler middleware(Handler handler) { return DService.middleware( handler: handler, certificate: (key) => Env.read(key)!, data: ResponseDataModel.fromJSON, ); }
Configuration class for defining Cross-Origin Resource Sharing (CORS) policies in a Dart backend application.
File:
_middleware.dart
Handler middleware(Handler handler) { return handler.use( Cors( accessControlAllowOrigin: ['*'], accessControlAllowMethods: [HttpMethod.get, HttpMethod.post], accessControlAllowHeaders: [Header.contentType, Header.authorization], accessControlAllowCredentials: false, accessControlExposeHeaders: [Header.date], accessControlMaxAge: Duration(hours: 24) ).handler, ); }
Abstract class representing headers used in CORS policies. It has 98 child class extending this class.
Header header = ContentType();
print(header); // 'Content-Type'
Generate simple random key identifier
String id = DService.randomID();
A set of mostly used typedefs in dart.
Typedef | Original |
---|---|
JSON | Map<String, dynamic> |
Offers a solution to simplify the boilerplate code commonly associated with using StatefulWidget. By providing a clean and efficient approach, it enhances the developer experience. Designed with convenience and simplicity in mind, AppStateWidget streamlines the development process, allowing you to focus on building intuitive user interfaces without getting bogged down by repetitive code.
To use it, you're going to need extending this class like this
class MyClass extends DWidget {
const MyClass({super.key});
@override
Map<String, dynamic> data(DState state){
return {'controller': TextEditingController()};
}
@override
void onPreparation(DState state){
state.value<TextEditingController>('controller').text = 'Loading';
}
@override
Widget onStart(DState state){
return TextField(controller: state.value<TextEditingController>('controller'));
}
void onReady(DState state){
state.value<TextEditingController>('controller').text = 'Data Loaded';
}
@override
void onFinish(DState state){
state.value<TextEditingController>('controller').dispose();
}
}
and you can also get [DState] in its child, by calling this
DInherited.of(context);
or get the data in [DState] with this
context.value<TextEditingController>("controller");
also to cell setState we change it to
state.update();
A widget that listens to changes in a ChangeNotifier
and rebuilds its child widgets based on the changes.
final changeNotifier = ScrollController();
return DChangeBuilder(
value: changeNotifier,
builder: (context, value, child) {
/* Your code here */
},
child: AnotherWidget(),
);
A generic InheritedWidget for providing an object to its descendants.
This is to set the value
DProvider<MyData>(
value: 'Test',
child: MyWidget(),
);
and this way to get the value
var value = context.provider.value;
print(value); // 'Test'
A wrapper around ExpansionTile
to listen changes of its state.
DTileWrapper((isExpanded) {
return ExpansionTile(...);
});
For dart doc generated document, you can see it in this