API Docs are available.
Android | iOS | MacOS | Web | Linux | Windows |
---|---|---|---|---|---|
✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Add this line to pubspec.yaml
dependencies:
nb_utils: <latest_version>
Import package
import 'package:nb_utils/nb_utils.dart';
Initialize nb_utils in main.dart file for initializing Shared Preferences and other variables.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initialize();
runApp(MyApp());
}
Now, add navigatorKey in your MaterialApp or CupertinoApp
return MaterialApp(
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
home: HomePage(),
);
BuildContext parameter is added to onAccept and onCancel in showConfirmDialogCustom method.
Checkout here Dev Library Contributors
/// Add a Google Logo
/// Add size parameter for custom size - Default is 24
GoogleLogoWidget(),
/// You can use your preferred State Management technique
Loader().visible(mIsLoading),
/// AppBar widget
appBarWidget(
"Title",
),
/// Timer widget
TimerWidget(
function: () {
// Do something
},
child: Text('Your Widget'),
duration: 10.seconds,
),
SettingSection(
title: Text('Account Management', style: boldTextStyle(size: 24)),
subTitle: Text('Control your account', style: primaryTextStyle()), // Optional
items: [
SettingItemWidget(
title: 'Hibernate account',
subTitle: 'Temporary deactivate your account',
decoration: BoxDecoration(borderRadius: radius()),
trailing: Icon(Icons.keyboard_arrow_right_rounded, color: context.dividerColor),
onTap: () {
//
}
),
SettingItemWidget(
title: 'Close account',
subTitle: 'Learn about your options, and close your account if you wish',
decoration: BoxDecoration(borderRadius: radius()),
trailing: Icon(Icons.keyboard_arrow_right_rounded, color: context.dividerColor),
onTap: () {
//
},
)
],
),
//SettingItem
SettingItemWidget(
title: "Title",
onTap: () {
//Your Logic
},
trailing: Icon(Icons.home_sharp), // Optional
leading: Icon(Icons.arrow_forward_ios_rounded), // Optional
subTitle: "Subtitle", // Optional
),
/// Default AppButton
/// Use AppButton on your app to try more properties
AppButton(
text: "Submit",
color: Colors.green, // Optional
onTap: () {
//Your logic
},
),
UL(
symbolType: SymbolType.Numbered,
children: [
Text('Hi', style: primaryTextStyle()),
Text('Hello', style: primaryTextStyle()),
Text('How are you?', style: primaryTextStyle()),
],
),
/// Use AppTextField on your app to try more properties
/// Use Form Validate to validate all AppTextField
/// Inbuilt Email Validator, Automatic email keyboard type
AppTextField(
controller: TextEditingController(), // Optional
textFieldType: TextFieldType.EMAIL,
decoration: InputDecoration(labelText: 'Email', border: OutlineInputBorder()),
),
/// Default Min Lines 4
AppTextField(
controller: TextEditingController(), // Optional
textFieldType: TextFieldType.MULTILINE,
decoration: InputDecoration(labelText: 'Address', border: OutlineInputBorder()),
),
/// Automatic password obscure, Show/Hide Password Option
AppTextField(
controller: TextEditingController(), // Optional
textFieldType: TextFieldType.PASSWORD,
decoration: InputDecoration(labelText: 'Password', border: OutlineInputBorder()),
),
HoverWidget(
builder: (context, bool isHovering) {
return Container(
/// isHovering will be true when you hover on it.
color: isHovering ? Colors.yellow : Colors.blue,
)
}
),
/// Build Horizontal List widget without giving specific height to it.
HorizontalList(
itemBuilder: (BuildContext context, int index) {
return AnyWidget();
},
itemCount: 25,
),
RatingBarWidget(
rating: initialRating,
onRatingChanged: (aRating) {
rating = aRating;
},
),
/// Make your Flutter App Responsive in any device out there with Responsive widget
Responsive(
mobile: MobileWidget(),
tablet: TabletWidget(), // Optional
web: WebWidget(), // Optional
),
TextIcon(
text: 'Your text',
prefix: AnyWidget(), // Optional
suffix: AnyWidget(), // Optional
),
DotIndicator(
pageController: pageController,
pages: list,
),
/// Use SnapHelperWidget to handle loading and error widget automatically
/// Still you can specify custom Loader Widget and Error Widget
SnapHelperWidget<T>(
future: future,
onSuccess: (data) {
return AnyWidget();
},
),
DottedBorderWidget(
child: Container(
height: 100,
width: 100,
),
),
Marquee(
direction: Axis.horizontal,
animationDuration: Duration(milliseconds: 100),
pauseDuration: Duration(milliseconds: 100),
child: Text("Please enter a long text to see the effect of the marquee widget"),
),
/// Show Dialog with Default Animation
showInDialog(context, builder: (context) => dialogWidget());
/// Show Dialog with Rotate Animation
showInDialog(context, builder: (context) => dialogWidget(), dialogAnimation: DialogAnimation.ROTATE);
/// Show Dialog with Scale Animation
showInDialog(context, builder: (context) => dialogWidget(), dialogAnimation: DialogAnimation.SCALE);
/// Show Dialog with Top to Bottom Animation
showInDialog(context, builder: (context) => dialogWidget(), dialogAnimation: DialogAnimation.SLIDE_TOP_BOTTOM);
/// Show Dialog with Bottom to Top Animation
showInDialog(context, builder: (context) => dialogWidget(), dialogAnimation: DialogAnimation.SLIDE_BOTTOM_TOP);
/// Show Dialog with Left to Right Animation
showInDialog(context, builder: (context) => dialogWidget(), dialogAnimation: DialogAnimation.SLIDE_LEFT_RIGHT);
/// Show Dialog with Right to Left Animation
showInDialog(context, builder: (context) => dialogWidget(), dialogAnimation: DialogAnimation.SLIDE_RIGHT_LEFT);
/// Show Confirmation Dialog
/// Second parameter is title
showConfirmDialog(
context,
'Do you want to logout from the app?',
onAccept: (context) {
//
},
);
/// Open a new screen
HomePage().launch(context);
/// Animate the new page (Slide, Rotate, Scale, Fade)
HomePage().launch(context, pageRouteAnimation: PageRouteAnimation.Slide);
/// Remove all screens from back stack and opens new screen
HomePage().launch(context, isNewTask: true);
// Returns to previous Screen
finish(context);
// Returns to previous Screen with a result
finish(context, object);
/// Toast a String
toast('This is a string');
/// Prints only if in debug or profile mode - (parameter is Object)
log('Your string');
/// Enter FullScreen Mode (Hides Status Bar and Navigation Bar)
enterFullScreen();
/// Unset Full Screen to normal state (Now Status Bar and Navigation Bar Are Visible)
exitFullScreen();
// Basic
snackBar(context, title: 'Sample toast'),
// Enhanced
snackBar(
context,
title: 'Sample toast',
textColor: Colors.blue,
backgroundColor: Colors.white,
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: radius(30)),
margin: EdgeInsets.all(16),
duration: 3.seconds,
);
/// Shared Preferences
/// setValue method has (String key, dynamic value) parameters
/// add a Double in SharedPref
await setValue("key", 20.0);
/// add a bool in SharedPref
await setValue("key", false);
/// add a int in SharedPref
await setValue("key", 10);
/// add a String in SharedPref
await setValue("key", "value");
/// add a String List in SharedPref
await setValue("key", ['value', 'value', 'value']);
/// Returns a Bool if exists in SharedPref
/// You can set a default value if it returns null
getBoolAsync("key");
/// Returns a Double if exists in SharedPref
getDoubleAsync("key");
/// Returns a Int if exists in SharedPref
getIntAsync("key");
/// Returns a String if exists in SharedPref
getStringAsync("key");
/// Returns a JSON if exists in SharedPref
getJSONAsync("key");
/// Remove a key from SharedPref
await removeKey("key");
/// Returns List of Keys that matches with given Key
getMatchingSharedPrefKeys('key')
/// With custom height and width
AnyWidget().withSize(height: 25, width: 50);
/// With custom width
AnyWidget().withWidth(25);
/// With custom height
AnyWidget().withHeight(100);
/// return padding top
AnyWidget().paddingTop(2);
/// return padding left
AnyWidget().paddingLeft(4);
/// return padding right
AnyWidget().paddingRight(8);
/// return padding bottom
AnyWidget().paddingBottom(16);
/// return padding all
AnyWidget().paddingAll(8);
/// return custom padding from each side
AnyWidget().paddingOnly();
/// return padding symmetric
AnyWidget().paddingSymmetric();
/// set visibility
/// true/false
AnyWidget().visible(true);
/// add custom corner radius each side
AnyWidget().cornerRadiusWithClipRRectOnly(topLeft: 10, bottomRight: 12);
/// add corner radius
AnyWidget().cornerRadiusWithClipRRect(20);
/// set widget visibility
/// true/false
AnyWidget().withVisibility(true);
/// add animated opacity to parent widget
AnyWidget().opacity(opacity: 0.2);
/// add rotation to parent widget
AnyWidget().rotate(angle: 1.2);
/// add scaling to parent widget
AnyWidget().scale(scale: 2.0);
/// set parent widget in center
AnyWidget().center();
/// add tap to parent widget
AnyWidget().onTap(() {
//
});
/// Wrap with ShaderMask widget
AnyWidget().withShaderMask([Colors.black, Colors.red]);
/// Wrap with ShaderMask widget Gradient
AnyWidget().withShaderMaskGradient(LinearGradient(colors: [Colors.black, Colors.red]));
/// add Expanded to parent widget
AnyWidget().expand();
/// add Flexible to parent widget
AnyWidget().flexible();
/// add FittedBox to parent widget
AnyWidget().fit();
/// Validate given widget is not null and returns given value if null.
AnyWidget().validate();
/// Validate given widget is not null and returns given value if null.
AnyWidget().withTooltip(msg: "Hello");
/// Returns how much time ago from timestamp
/// The number of milliseconds that have passed since the timestamp
/// You can use .timeAgo on a DateTime object like this
String result = DateTime.now().timeAgo;
int difference = DateTime.now().millisecondsSinceEpoch;
/// Converts the time difference to a number of seconds.
countSeconds(difference);
/// Converts the time difference to a number of minutes.
countMinutes(difference);
/// Converts the time difference to a number of hours.
countHours(difference);
/// Converts the time difference to a number of days.
countDays(difference);
/// Converts the time difference to a number of weeks.
countWeeks(difference);
/// Converts the time difference to a number of months.
countMonths(difference);
/// Converts the time difference to a number of years.
countYears(difference);
/// Returns True/False
String example = "";
/// Check URL validation
example.validateURL();
/// Check email validation
example.validateEmail();
/// Check phone validation
example.validatePhone();
/// Return true if given String is Digit
example.isDigit();
/// Check weather String is alpha or not
example.isAlpha();
/// Check weather String is Json or not
example.isJson();
/// Copy String to Clipboard
example.copyToClipboard();
/// for ex. add comma in price
example.formatNumberWithComma();
/// Get Color from HEX String
example.toColor();
/// It reverses the String
example.reverse;
/// It return list of single character from String
example.toList();
/// Returns true if given String is null or isEmpty
example.isEmptyOrNull;
/// Check null string, return given value if null
example.validate();
/// Capitalize First letter of a given String
example.capitalizeFirstLetter();
/// Returns if its type image
example.isImage;
/// Returns if its type Audio
example.isAudio;
/// Returns if its type Video
example.isVideo;
/// Returns if its type Txt
example.isTxt;
/// Returns if its type Doc
example.isDoc;
/// Returns if its type Excel
example.isExcel;
/// Returns if its type PPT
example.isPPT;
/// Returns if its type Apk
example.isApk;
/// Returns if its type Pdf
example.isPdf;
/// Returns if its type Html
example.isHtml;
/// Pass the Pattern
/// Splits from a [pattern] and returns remaining String after that
example.splitAfter(Patterns.apk);
/// Splits from a [pattern] and returns String before that
example.splitBefore(Patterns.audio);
/// It matches the String and returns between [startPattern] and [endPattern]
example.splitBetween("d", "g");
/// Return int value of given string
example.toInt();
/// Get YouTube Video ID
example.toYouTubeId();
/// Returns YouTube thumbnail for given video id
example.getYouTubeThumbnail();
/// Removes white space from given String
example.removeAllWhiteSpace();
/// Returns only numbers from a string
example.getNumericOnly(example);
/// Return average read time duration of given String in seconds
example.calculateReadTime();
/// Return number of words in a given String
example.countWords();
/// Generate slug of a given String
example.toSlug();
/// returns searchable array for Firebase Database
example.setSearchParam();
ScrollController scrollController = ScrollController();
/// animate to top
scrollController.animToTop();
/// animate to Bottom
scrollController.animToBottom();
/// animate to specific position
scrollController.animateToPosition(20.0);
/// jump to the start of the list without animation
scrollController.jumpToTop();
/// jump to the end of the list without animation
scrollController.jumpToBottom();
/// Apply Bold TextStyle
Text(item.title.validate(), style: boldTextStyle())
/// Apply Primary TextStyle
Text(item.title.validate(), style: primaryTextStyle())
/// Apply Secondary TextStyle
Text(item.title.validate(), style: secondaryTextStyle())
/// Apply default BoxDecoration with default shadow and border radius
Container(
decoration: boxDecorationDefault(), // You can modify based on your preference
),
/// FocusNode
requestFocus(NODE_VARIABLE);
nextFocus(NODE_VARIABLE);
/// Handle error and loading widget when using FutureBuilder or StreamBuilder
/// "snap" is the snapShot value we get from FutureBuilder or StreamBuilder
return snapWidgetHelper(snap);
/// See the example below. You can user FutureBuilder or StreamBuilder.
FutureBuilder(
builder(_, snap) {
if (snap.hasData) {
return YourWidget();
} else {
/// This function will handle loading and error automatically.
/// You can modify loading and error widget in parameters.
return snapWidgetHelper(snap);
}
}
)
/// return screen width
context.width();
/// return screen height
context.height();
/// Theme color or value from context
context.primaryColor;
context.theme.text.subtitle.color;
/// return current time in milliseconds
int currentMillisecondTimeStamp = currentMillisecondsTimeStamp();
/// return current timestamp
int currentTimeStamps = currentTimeStamp();
/// return true if given year is an leap year
/// leapYear(year)
bool isLeapYear = leapYear(2000);
/// returns number of days in given month
/// daysInMonth(monthNum, year)
int dayInMonthTotal = daysInMonth(2, 2000);
/// Returns Time Ago
/// only on datetime object
/// Just Now, 2 minutes ago, 1 hour ago, 1 day ago
String timeAgo = DateTime.now().timeAgo;
/// Change status bar Color and Brightness
setStatusBarColor(Colors.blue);
/// Show Status Bar
showStatusBar();
/// Hide Status Bar
hideStatusBar();
/// Set orientation to portrait
setOrientationPortrait();
/// Set orientation to landscape
setOrientationLandscape();
/// Get current PlatformName as a String
platformName();
/// Invoke Native method and get result
var data = await invokeNativeMethod(CHANNEL_NAME, METHOD_NAME, [dynamic arguments]);
AppButton(
text: "Add",
onTap: () {
showConfirmDialogCustom(
context,
title: "Do you want to add this item?",
dialogType: DialogType.ADD,
onAccept: () {
snackBar(context, title: 'Added');
},
);
},
),
AppButton(
text: "Delete",
onTap: () {
showConfirmDialogCustom(
context,
title: "Delete 89 files permanent?",
dialogType: DialogType.DELETE,
onAccept: () {
snackBar(context, title: 'Deleted');
},
);
},
),
AppButton(
text: "Update",
onTap: () {
showConfirmDialogCustom(
context,
title: "Do you want to update this item?",
dialogType: DialogType.UPDATE,
onAccept: () {
snackBar(context, title: 'Updated');
},
);
},
),
AppButton(
text: "Confirmation with Custom Image",
onTap: () async {
showConfirmDialogCustom(
context,
title: "Do you want to logout from the app?",
dialogType: DialogType.CONFIRMATION,
centerImage: 'URL',
onAccept: () {
//
},
onCancel: () {
//
},
height: 300,
width: 400,
);
},
),
AppButton(
text: "Confirmation",
onTap: () {
showConfirmDialogCustom(
context,
onAccept: () {
snackBar(
context,
title: 'Confirmed',
snackBarAction: SnackBarAction(label: 'label', onPressed: () {}),
);
},
);
},
),
Please file feature requests and bugs at the issue tracker.