flutter pro tools
flutter_pro_tools
is a comprehensive utility package designed to enhance your Flutter development
experience. It provides a variety of tools and widgets, including navigation helpers, localization
support, snackBar utilities, modal bottom sheets, Firebase integration, local data storage,
responsive text, and socket connection management.
Features
- Navigation Helpers: Simplify navigation with global keys and custom route animations.
- Localization Support: Easily translate and localize text within your app.
- SnackBar Utilities: Quickly display customizable snackBars for notifications and warnings.
- Modal Bottom Sheets: Show customizable modal bottom sheets with various configurations.
- Firebase Integration: Initialize Firebase, handle notifications, and manage Firebase messaging.
- Local Data Storage: Save and retrieve encrypted local data.
- Responsive Text: Text widgets that adapt to different screen sizes.
- Socket Connection: Efficiently manage socket connections.
- API Requests: Simplify making HTTP requests (GET, POST, DELETE, PUT) with error handling and logging.
- Image Handling: Choose and crop images with specified settings.
- Geolocation: Detect and handle user location with permission checks.
- Camera Capture Utility: Captures an image using the device's camera, crops the image, and ensures it does not exceed the specified file size.
Usage
Importing the Package In any Dart file where you want to use the utilities from flutter_pro_tools, import the package:
import 'package:flutter_pro_tools/main.dart';
Then run this command to add necessary translate file and directory:
dart run flutter_pro_tools:init_data
Examples
Using navigation and snackBar keys
Add navigatorKey and snackBarKey to material app to use navigation and show snack message
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorGlobalKey,
scaffoldMessengerKey: snackBarGlobalKey,
home: MyHomePage(),
);
}
}
Navigation push
Pushes a new page onto the navigation stack.
function() async {
NavigationTools.push(YourPage());
NavigationTools.pushToRoute("route name");
}
Navigation replace
Replaces the current page with a new page.
function() async {
NavigationTools.replace(YourPage());
NavigationTools.replaceToRoute("route name");
}
Navigation and remove all the previous routes
Navigate to a new page, and then remove all the previous navigation stack.
function() async {
NavigationTools.removeAllPreviousPages(YourPage());
NavigationTools.removeAllPreviousPagesToRoute("route name");
}
Check internet connection
Check if the connection available
function() async {
checkInternetConnection(function: () {
ShowMessage.success(message: 'Hello, connection with success!');
});
}
Showing a snack bar
Display a simple snackBar for notifications:
function() async {
ShowMessage.success(message: 'Hello, this is a snackBar!');
}
Showing a warning snack bar
Display a warning snackBar
function() async {
ShowMessage.warning(message: 'Warning! Something might be wrong.');
}
Showing a bar modal bottom sheet
Show a customizable bar modal bottom sheet
function() async {
FlutterProTools.showBarModal(
page: MyCustomPage(),
enableDrag: true,
isDismissible: true,
);
}
Showing a modal bottom sheet
Show a modal bottom sheet
function() async {
FlutterProTools.showMaterialModel(
const MyCustomPage(),
);
}
Get current size
Retrieves the current size of the screen or widget context from the snackBarKey
context.
function() {
Size? screenSize = DeviceTools.screenSize;
if (screenSize != null) {
logFile(
message: "Width: ${screenSize.width}, Height: ${screenSize.height}",
name: "Screen size");
}
}
Firebase initialization
Initialize Firebase and request notification permissions:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// add firebase project config
NotificationManager.setFirebaseProjectConfig(
apiKey: 'your_api_key',
appId: 'your_app_id',
messagingSenderId: 'your_messaging_sender_id',
projectId: 'your_project_id',
);
if (!kIsWeb) {
// ask user for firebase permission and generate new token then send it to server
await NotificationManager.getFirebasePermissionAndToken(callback: onValue);
// init firebase background and all other firebase settings
await NotificationManager.initFlutterNotifications();
// Listens for incoming Firebase Cloud Messaging (FCM) messages and shows a notification
NotificationManager.firebaseMessaging(callback: (NotificationModel message) {
// Handle FCM message.
});
}
}
Remove All Notifications
Remove all notifications from background
function() {
NotificationManager.cancelAllNotification();
}
Remove Notification by id
Remove notifications from background by notification id
function() {
NotificationManager.cancelNotification(notificationId: 1);
}
Saving and retrieving local data
Save data and retrieve in you app locally
// Save data locally
function() async {
DataStorageTools.storeInteger(
key: 'userAge', value: 30); // Save a integer locally using SharedPreferences:
await DataStorageTools.storeBoolean(
key: 'isLoggedIn', value: true); // Saves a boolean to local storage.
await DataStorageTools.storeString(
key: "username", value: "JohnDoe");
await DataStorageTools.storeListOfString(
key: "list", value: ["index1", "index2", "index3"]
);
String? username =
await DataStorageTools.getString(key: 'username'); // Retrieves a string from local storage.
DataTools.removeByKey(
key: 'username'); // Removes a key-value pair from local storage.
await DataStorageTools.getBoolean(
key: 'isLoggedIn'); // Retrieves a boolean from local storage.
await DataStorageTools.getInteger(
key: 'userAge'); // Retrieves an integer from local storage.
await DataStorageTools.getListOfString(
key: 'list'); // Retrieves an list of string from local storage.
ShowMessage.alert(
title: "Local Storage",
translateTitle: false,
content: ResponsiveText(
"${FlutterProTools.translate("saved_username")}: $username",
),
);
}
Responsive text widget
Use the ResponsiveText widget to automatically adjust text size based on screen size:
import 'package:flutter/material.dart';
import 'package:flutter_pro_tools/main.dart';
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: ResponsiveText('Home Page'),
),
body: Center(
child: ResponsiveText('This text is responsive!'),
),
);
}
}
Set portrait device
Sets the device orientation to portrait only:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await DeviceTools.setDeviceOrientation(orientationType);
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
Read current value
Reads the current value from the specified ChangeNotifierProvider
function() {
readStatus(providerVal);
}
Recall API
Re-calls the given API by refreshing the provided Refreshable provider.
function() {
ApiRequest.recallAPI(provider);
}
Check for app update
Checks if a new version of the app is available by comparing the current platform version with the provided app version.
function() async {
await checkForUpdate(appVersion: "1.2.3");
}
Translate
Please add riverpod package in pubspec.yaml
dependencies:
flutter_riverpod: ^2.5.1
Then add this functions:
class MyApp extends ConsumerWidget {
const MyApp({super.key, required this.page});
// This widget is the root of your application.
@override
Widget build(BuildContext context, WidgetRef ref) {
var state = ref.watch(languageStatus);
return MaterialApp(
locale: state.locale,
supportedLocales: AppLocale.supportedLocale(),
localeResolutionCallback: AppLocale.localeResolutionCallback,
localizationsDelegates: AppLocale.localizationsDelegates(),
);
}
}
You need it add this in each page you need to translate:
class MyApp extends ConsumerWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context, WidgetRef ref) {
var state = ref.watch(languageStatus); // this line
return MaterialApp(
home: const HomePage(),
locale: state.locale,
);
}
}
Translates a key into the current locale's language
String translatedText = getTranslate('hello');
To change application language (supported only arabic and english):
function() {
LanguageManagement.getCurrentLanguage == "en"
? languageState.changeLanguage('ar')
: languageState.changeLanguage('en');
}
To change the current language from outside the page (e.g: controller):
changeLanguage() {
LanguageManagement.changeLanguage('ar');
}
Get current language
To get current app language
function() async {
String language = LanguageManagement.getCurrentLanguage;
}
Close page
Closes the current modal or bar modal.
function() {
DeviceTools.closePage();
}
Close keyboard
Closes the keyboard if it is open.
function() {
DeviceTools.closeKeyboard();
}
Get request
- Notice that the response in this plugin handle to return as Map<String, dynamic> Performs a GET HTTP request.
function() {
ApiRequest.get(
url: "https://jsonplaceholder.typicode.com/posts/1",
response: (data) =>
FlutterProTools.showAlertDialog(
title: "GET Request",
content: ResponsiveText(
data.body,
),
),
);
}
Send request
Performs a POST HTTP request.
function() {
ApiRequest.send(
url: 'https://api.example.com/data',
data: {name: "name example"},
File ? file : file,
String ? jsonFileKeyName : jsonFileKeyName,
authorization: 'Bearer token',
response: (http.Response response) {
print(response.body);
},
);
}
Delete request
Performs a DELETE HTTP request.
function() {
ApiRequest.delete(
url: 'https://api.example.com/data',
authorization: 'Bearer token',
response: (http.Response response) {
print(response.body);
},
);
}
Update request
Performs a PUT HTTP request.
function() {
ApiRequest.update(
url: 'https://api.example.com/data',
data: {name: "name example"},
File ? file : file,
String ? jsonFileKeyName : jsonFileKeyName,
authorization: 'Bearer token',
response: (http.Response response) {
print(response.body);
},
);
}
Show material model
Shows a material bottom sheet modal.
function() {
FlutterProTools.showMaterialModel(
const ModelPage(),
);
}
Show alert dialog
Shows an alert dialog.
function() {
ShowMessage.alert(
content: Text('This is an alert dialog.'),
title: 'Alert',
);
}
Show error alert dialog
Shows an error alert dialog and executes a function when "OK" is pressed.
function() {
ShowMessage.error(callback: () {
logFile(
message: 'Retry action',
name: "Error message");
});
}
Show notification
Shows a notification with a title and body.
function() {
FlutterProTools.showNotification(
title: 'Notification Title',
body: 'This is the body of the notification.',
otherData: {
"title": "Payload title",
"body": "Payload body",
},
callback: (data) {
logFile(
message: data.payload!,
name: "Show notification");
});
}
Add those to android -> app -> build.gradle
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.5'
}
LaunchURL
Navigate to external url
function() {
openURL(url: "https://google.com", callback: () => print(ok));
}
Check for VPN connection
Check if the device connected to VPN
function() async {
bool result = await isVpnActive();
}
Loading progress dialog
Show loading dialog during request processing
function() {
FlutterProTools.showLoadingDialog();
}
Close loading dialog
Close loading dialog when request ended
function() {
FlutterProTools.dismissLoadingDialog();
}
Log file
To show log inside your app
function() {
logFile(
message: "this is log file",
name: "Log file");
}
Pretty log file
To show log inside your app with Map data type
function() {
prettyLogFile(message: data);
}
Get date formated
get the date formated in form yyyy-MM-dd
function() {
getDateFormatByDate(date);
}
Get random number
get random number length :
function() {
logFile(
message: getInteger(6),
name: "Get integer number");
}
File handling
Choose file from and crop images with specified settings.
function() async {
File? result = await FileManagement.chooseFile();
}
Geolocation
Detect the user's current location.
function() async {
Position? result = await LocationManagement.detectMyLocation();
}
Add the following to your "gradle.properties" file:
android.useAndroidX=true
android.enableJetifier=true
Make sure you set the compileSdkVersion in your "android/app/build.gradle" file to 34:
android {
compileSdkVersion 34
...
}
Add the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
iOS Info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to provide better service</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need access to your location at all times</string>
Add the following if you want to receive you position in background to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
ios Info.plist:
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
Image cropper
Choose and crop images with specified settings.
function() async {
XFile result = await FileManagement.cropImage();
}
Add in AndroidManifest.xml
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
Connect to socket io
Initializes the WebSocket connection with the given socketURL. Connects to the WebSocket server. Listens for connection and disconnection events to update the checkSocketConnectionStatus and displays a snack bar message.
function() {
SocketIoManagement.initConnection(
socketURL: socketURL,
callback: (data) {
logFile(
message: data.toString(),
name: "Init connection");
},
);
}
Send data through socket io
Sends a message to the server via the socket io
function() {
SocketIoManagement.post(event: 'event', data: data);
}
Get data through socket io
Listens for a specific event from the server.
function() {
SocketIoManagement.get(
event: "event",
callback: (data) async {
logFile(
message: data.toString(),
name: "Get data socket");
},
);
}
Send and get data through socket io
Sends a message to the server with an acknowledgment callback.
function() {
SocketIoManagement.withAck(
event: 'event',
data: {"first_name": "test first name", "last_name": "test last name", "email": "email"},
callback: (data) {
logFile(
message: data.toString(),
name: "With ack socket");
},
);
}
Device authorization
Check if user device support locale auth like finger print or pattern
function() {
AuthenticationManagement.checkLocalAuth(calback: () {
logFile(
message: "device authorization with success",
name: "Check local auth");
}, isDeviceNotSupported: () {
logFile(
message: "device not supporting pattern or finger print",
name: "Check local auth");
}
);
}
You need to add those on AndroidManifest.xml:
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
ios Info.plist:
<key>NSFaceIDUsageDescription</key>
<string>We use Face ID to authenticate your identity securely.</string>
Get user location with steam
Listens to position updates and triggers a callback function for each update.
function() {
LocationManagement.getCurrentPosition(
(onPositionUpdate) {
logFile(
message: "my current position is ${onPositionUpdate.latitude},${onPositionUpdate
.longitude}",
name: "Get current position");
},
);
}
You need to add those on AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
iOS (Info.plist):
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to provide better service</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need access to your location at all times</string>
Get distance
Calculates the distance (in meters) between two geographic coordinates.
function() async {
var double = await LocationManagement.getDistance(
startLatitude: myLatitude,
startLongitude: myLongitude,
endLatitude: distinationLatitude,
endLongitude: distinationLongitude,
);
logFile(
message: "the distance is $double",
name: "Get distance");
}
Get speed
Stream speed continuously (e.g., for real-time tracking)
function() async {
String speed = await LocationManagement.getSpeedInKMH();
logFile(
message: "the speed is $speed",
name: "Get speed");
}
Otp sing in
Sign in with phone number and redirect after successful sign-in using firebase phone number auth otp
function() {
AuthenticationManagement.signInWithPhoneNumber(
phoneNumber: '123456789',
redirectPage: Example(),
waitingTime: 100,
onError: () {},
onComplete: () async {
await ApiRequest.get(
url: "https://jsonplaceholder.typicode.com/posts/1",
response: (data) =>
ShowMessage.alert(
title: "GET Request",
content: ResponsiveText(
data.body,
),
),
);
ShowMessage.success(message: 'success');
}
);
}
Shareable link
The shareableLink function allows you to share a given URL using the device's native sharing capabilities.
function() async {
await ShareService.shareLink(link: "https://google.com");
}
Send sms otp
The sendSmsOtp function is designed to send a one-time password (OTP) via SMS.
function() async {
await AuthenticationManagement.sendSmsOtp(smsSenderUrl: url,
companyName: 'company name',
phone: '123456789');
}
Convert number to arabic words
Converts an integer into Arabic words.
function() {
String result = convertToArabicWords(123);
logFile(
message: "the result is $result",
name: "Convert number to arabic words");
}
Open app setting
Open the app setting to enable location permission.
function() async{
await LocationManagement.openSetting();
}
License
This project is licensed under a Custom App Usage License. You are permitted to use this software as part of your application, but you are not allowed to copy, modify, merge, publish, distribute, sublicense, or sell copies of the software, or permit others to do so.