nb_utils 4.3.0+4
nb_utils: ^4.3.0+4 copied to clipboard

This package helps you daily usable function and ready made Widgets with ease.

Pub Package GitHub: bhoominn GitHub: bhoominn

Show some love and like to support the project #

Documentation #

API Docs are available.

Platform Support #

AndroidiOSMacOSWebLinuxWindows
✔️✔️✔️✔️✔️✔️

Installation #

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());
}

Examples #

Ready to Use widgets with Optional Parameters #

/// 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",
),
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: () {
        //
      },
    )
  ],
),

SettingSection

//SettingItem
SettingItemWidget(
   title: "Title",
   onTap: () {
       //Your Logic
   },
   trailing: Icon(Icons.home_sharp), // Optional
   leading: Icon(Icons.arrow_forward_ios_rounded), // Optional
   subTitle: "Subtitle", // Optional
),

SettingItemWidget

/// 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
AppTextField(
    controller: TextEditingController(), // Optional
    textFieldType: TextFieldType.EMAIL,
    decoration: InputDecoration(labelText: 'Email', border: OutlineInputBorder()),
),
AppTextField(
    controller: TextEditingController(), // Optional
    textFieldType: TextFieldType.ADDRESS,
    decoration: InputDecoration(labelText: 'Address', border: OutlineInputBorder()),
),
AppTextField(
    controller: TextEditingController(), // Optional
    textFieldType: TextFieldType.PASSWORD,
    decoration: InputDecoration(labelText: 'Password', border: OutlineInputBorder()),
),

AppTextField

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,
),

HorizontalList

RatingBarWidget(
    rating: initialRating,
    onRatingChanged: (aRating) {
        rating = aRating;
    },
),

RatingBarWidget

/// 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(
    future: future,
    onSuccess: (data) {
        return AnyWidget();
    },
),
DottedBorderWidget(
    child: Container(
        height: 100,
        width: 100,
    ),
),

DottedBorderWidget

AppButton(
  text: "Add",
  onTap: () {
    showConfirmDialogCustom(
      context,
      title: "Do you want to add this item?",
      dialogType: DialogType.ADD,
      onAccept: () {
        snackBar(context, title: 'Added');
      },
    );
  },
),

Add Confirmation Dialog

AppButton(
  text: "Delete",
  onTap: () {
    showConfirmDialogCustom(
      context,
      title: "Delete 89 files permanent?",
      dialogType: DialogType.DELETE,
      onAccept: () {
        snackBar(context, title: 'Deleted');
      },
    );
  },
),

Delete Confirmation Dialog

AppButton(
  text: "Update",
  onTap: () {
    showConfirmDialogCustom(
      context,
      title: "Do you want to update this item?",
      dialogType: DialogType.UPDATE,
      onAccept: () {
        snackBar(context, title: 'Updated');
      },
    );
  },
),

Update Confirmation Dialog

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,
    );
  },
),

Custom Confirmation Dialog

AppButton(
  text: "Confirmation",
  onTap: () {
    showConfirmDialogCustom(
      context,
      onAccept: () {
        snackBar(
          context,
          title: 'Confirmed',
          snackBarAction: SnackBarAction(
              label: 'label', onPressed: () {}),
        );
      },
    );
  },
),

Default Confirmation Dialog

Some useful method or extensions you will ever need #


/// Open a new screen
HomePage().launch(context);

/// Remove all screens from back stack and opens new screen
HomePage().launch(context, isNewTask: true);

// Returns to previous Screen
finish(context);
/// Enable click on any widget
AnyWidget().onTap(() {
  //
});
/// Toast a String
toast('This is a string');

Shared Preferences #


/// 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");

Widgets Extensions, Methods #

/// 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 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");


Time formatter formatTime Extensions, Methods #

/// 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);

Strings Extensions, Methods #

/// 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();

Scroll Controller #

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();

TextStyles/Decorations/FocusNodes/Navigation/Toast/Context Methods #

 
/// 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())


/// types of decoration
Container(
    decoration: boxDecorationDefault(), // You can modify based on your preference
),

/// FocusNode
requestFocus(NODE_VARIABLE);
nextFocus(NODE_VARIABLE);

/// NAVIGATION Between Screen

///  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);
        }
    }
)

/// Toast a String
toast('This is a string');

/// Toast a String for a long duration
toastLong('This is a string');

/// Prints only if in debug or profile mode - (parameter is Object)
log('Your string');

/// return screen width
context.width();

/// return screen height
context.height();
    
/// Theme color or value from context
context.primaryColor;
context.theme.text.subtitle.color;

DateTime Extensions, Methods #

/// 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;

Systems Methods #

/// 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]);

Features and bugs #

Please file feature requests and bugs at the issue tracker.

If you want to give suggestion, please contact me via email - bhoominn@gmail.com #

Thank you :) #

33
likes
120
pub points
96%
popularity

Publisher

Unknown

This package helps you daily usable function and ready made Widgets with ease.

Homepage
Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (LICENSE)

Dependencies

connectivity, flutter, fluttertoast, shared_preferences

More

Packages that depend on nb_utils