Dart Fusion
A library that brings together a harmonious blend of essential tools, utilities, and components designed to supercharge my Dart projects.
Table of Contents
- Dart Fusion
- Dart Fusion CLI
- D Annotations
- D Assertions
- D Behavior
- D Builder
- D Exceptions
- D Extensions
- D Image
- D Log
- D Models
- D Overlay
- D Parse
- D Runner
- D Services
- D Typedefs
- D Widget
- D Change Builder
- D Provider
- D Tile Wrapper
Installation
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
Dart Fusion CLI
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
Usage
-
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
D Annotations is a set of class used as an indicator for Dart Fusion CLI
model generation
Usage
-
Model: Annotation of class as an indicator to generate a
fromJSON
,toJSON
andcopyWith
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 Assertions
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 anException
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 );
-
Response: A specialized
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
D Behavior is a custom scroll behavior for controlling the scrolling physics of scrollable widgets.
Usage
ScrollConfiguration(
behavior: DBehavior(
physics: BouncingScrollPhysics()),
child: ListView(),
);
D Builder
D Builder is a widget that builds its child using a custom builder function with optional data.
Usage
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
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 Exception: An exception containing
Response
value.throw ResponseException( response: Response( statusCode: 404, ) );
D Extensions
An extension collection of mostly used function in flutter project.
Number Extension
Extension on numeric types (int, double) to add utility methods for limiting values within a specified range.
- Min : Limit the minimum number of the extended value.
int min = 5.min(10); print(min); // 10
- Max : Limit the maximum number of the extended value.
double max = 100.0.max(10.0); print(max); // 10.0
- Limit : Limit number of the extended value in a certain range.
int number = 75.limit(0, 100); print(number); // 75
Integer Extension
Converts integer to a human-readable string representing bytes.
int bytes = 1048576;
String parse = bytes.toReadableBytes;
print(parse); // "1048.57 KB"
JSON Extension
Extension on the Map<String, dynamic> value.
- Merge : Merging one
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"}
- Of : Parse
dynamic
value inJSON
to givenObject
with an optionalonError
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"
- Maybe of : Parse
dynamic
value inJSON
to given nullableObject
.JSON value = {"primary": "1"}; String? primary = value.maybeOf<String>("primary"); print(primary); // "1" String? secondary = value.maybeOf<String>("secondary"); print(secondary); // null
BuildContext Extension
A set of extension collection on BuildContext
.
- Theme : A shortcut for calling
Theme.of(context)
.ThemeData theme = context.theme;
- Color : A shortcut for calling
Theme.of(context).colorScheme
.ColorScheme color = context.color;
- Text : A shortcut for calling
Theme.of(context).textTheme
.TextTheme text = context.text;
- Query : A shortcut for calling
MediaQuery.of(context)
.MediaQuery query = context.query;
- Size : A shortcut for calling
MediaQuery.sizeOf(context)
.Size suze = context.querySize;
- Width : A shortcut for calling
MediaQuery.sizeOf(context).width
.double width = context.width;
- Height : A shortcut for calling
MediaQuery.sizeOf(context).height
.double height = context.height;
- Is Phone : To check wether the screen width less than
400 px
or not.bool isPhone = context.isPhone;
- Is Desktop : To check wether the screen width more than
700 px
or not.bool isDesktop = context.isDesktop;
- Is Tablet : To check wether the screen width less than
400 px
and more than700 px
or not.bool isTablet = context.isTablet;
RequestContext Extension
A set of extension collection on RequestContext
.
- Method : A shortcut to get
HttpMethod
out ofRequestContext
.HttpMethod method = context.method;
- Is Get : Check whether request method is
HttpMethod.get
or not.bool isGET = context.isGET;
- Is Post : Check whether request method is
HttpMethod.post
or not.bool isPOST = context.isPOST;
- Is Put : Check whether request method is
HttpMethod.put
or not.bool isPUT = context.isPUT;
- Is Delete : Check whether request method is
HttpMethod.delete
or not.bool isDELETE = context.isDELETE;
- Is Web Socket : Check whether request method is a http request or websocket request.
bool isWS = context.isWebSocket;
- Parameter : A shortcut to get parameter from
RequestContext
.JSON parameter = context.parameter;
- Header : A shortcut to get header from
RequestContext
.JSON parameter = context.parameter;
- JWT Verify : A function to verify
JWT
Bearer Token.JWT jwt = await context.verify((key) => Env.read<String>(key));
List Extension
A set of extension collection on BuildContext
.
- To : Generate key index and value of its items.
List<String> texts = ["one", "two", "three"]; List<Widget> widgets = texts.to((index, item) => Text("$index: $item"));
- Limit : Safely limitting list on certain length.
List<int> integers = [1, 2, 3]; List<int> sublist = integers.limit(1, 100); print(sublist); // [2, 3]
DModel List Extension
Extending list of DModel
to get its toJSON values.
List<DModel> dmodels = [DModel(), DModel()];
List<JSON> jsons = dmodels.toJSON;
String Extension
Capitalizing the first letter of String
s.
String word = 'magnificent'.capitalize;
print(word); // Magnificent
D Image
A widget for displaying vector or bitmap images from different sources.
Usage
// 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');
D Log
A simple logging utility for printing log messages with customizable log levels.
Usage
Exception e = Exception('something');
DLog(e); // Exception: something
D Models
A collection of DModel
models.
-
D Model: Base dart model which consist
copyWith
,toJSON
,fromJSON
andtoString
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
, containingsuccess
status,message
and alsodata
that extendsDModel
class.ResponseModel( success: true, message: 'Successfully Fetching Data!', data: const ResponseDataModel());
-
Link Model: Link reference used in
ResponseModel
to indicate the relationship of resources.LinkModel( method: HttpMethod.get, description: 'Read User Detail', reference: '/user/123');
D Overlay
A builder widget that displays an overlay.
Usage
final overlay = DOverlay(builder: (context, progress, controller) => YourWidget());
GestureDetector(
onTap: () {
overlay.controller.display(context);
}
);
D Parse
A utility class for parsing mostly related to http request.
- HTTP Method Message : Parsing message of http method value like
DELETE
,GET
,HEAD
,OPTIONS
,PATCH
,POST
orPUT
.HttpMethod method = HttpMethod.get; final message = DParse.httpMethodMessage(method.name); print(message); // 'Data successfully loaded'
- HTTP Status Message : Parsing message of
statusCode
value inResponse
.Response response = Response(...); final message = DParse.httpStatusMessage(response.statusCode); print(message); // 'Not Found: The requested resource could not be found'
- Exception Message : Parsing error message from
Exception
.FormatException exception = FormatException('Unexpected end of input (at character 1)'); final message = DParse.exceptionMessage(exception); print(message); // 'Data is not exist'
D Runner
Runner class for `Dart Fusion CLI'.
- Asset Runner : Runner to scan asset and turn it into one model class.
- Model Runner : Runner to completing
DModel
, likecopyWith
,fromJSON
andtoJSON
. - Localization Runner : Runner to translate
Locale
and generate a model to be integrated witheasy_localization
.
Usage
Set this in your root main.dart
File:
main.dart
void main() { WidgetsFlutterBinding.ensureInitialized(); DartFusion.runner(const [AssetRunner(), ModelRunner(), LocalizeRunner()]); runApp(...); }
D Services
A set of service collection mosty used in dart backend.
MiddleWare
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, ); }
Cors
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, ); }
Header
Abstract class representing headers used in CORS policies. It has 98 child class extending this class.
Header header = ContentType();
print(header); // 'Content-Type'
Random ID
Generate simple random key identifier
String id = DService.randomID();
D Typedefs
A set of mostly used typedefs in dart.
Typedef | Original |
---|---|
JSON | Map<String, dynamic> |
D Widget
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.
Key Features
- Reduce Boilerplate With DWidget, you can significantly reduce boilerplate code when working with StatefulWidget. Say goodbye to excessive code blocks and welcome concise, elegant declarations.
- Improved Readability By abstracting away common patterns, the library ensures cleaner and more readable code, making it easier to comprehend and maintain your project.
- Easy to Use Implementing DWidget is straightforward. Just extend the class, override specific methods like onStart, onPreparation, onFinish, and let the magic happen.
- Data Passing Made Simple With a convenient data method, you can easily declare and pass data between the widget and its state, ensuring your data management is both efficient and organized.
Usage
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();
D Change Builder
A widget that listens to changes in a ChangeNotifier
and rebuilds its child widgets based on the changes.
Usage
final changeNotifier = ScrollController();
return DChangeBuilder(
value: changeNotifier,
builder: (context, value, child) {
/* Your code here */
},
child: AnotherWidget(),
);
D Provider
A generic InheritedWidget for providing an object to its descendants.
Usage
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'
D Tile Wrapper
A wrapper around ExpansionTile
to listen changes of its state.
Usage
DTileWrapper((isExpanded) {
return ExpansionTile(...);
});
Documentation
For dart doc generated document, you can see it in this
Libraries
- dart_fusion
- A library that brings together a harmonious blend of essential tools, utilities, and components designed to supercharge your Dart projects.