Surav Usage Guide
This guide provides an overview of how to use the ApiRequest class and the SuravLocal class for making HTTP requests and managing local data storage in a Flutter application using the Dio package.
Table of Contents
Installation
To use the ApiRequest and SuravLocal classes, you need to include the following dependencies in your pubspec.yaml file:
dependencies:
surav: ^1.0.27+2
flutter:
sdk: flutter
Run flutter pub get to install the dependencies.
Usage
Certainly! Here's a README for your SuravApp class:
SuravApp
SuravApp is a customizable wrapper around the MaterialApp widget provided by the Flutter framework. It provides additional features and customization options while maintaining compatibility with existing Flutter projects.
Features
-
Simplified Navigation: The
SuravAppwidget integrates with theSuravNavigateclass, which provides keys for managing the state of the navigator and scaffold messenger. -
Enhanced Debugging Tools: Easily toggle debugging features such as checkerboard layers and raster cache images to identify performance bottlenecks in your app.
-
Customizable Themes: Configure themes, including dark themes and high contrast themes, and specify animation curves and durations for theme transitions.
-
Locale Support: Set the initial locale, specify locale resolution callbacks, and manage supported locales to internationalize your app.
-
Dynamic Routing: Define routes and handle unknown routes using callback functions, providing flexibility in navigating through different screens.
Usage
To use SuravApp, simply instantiate it with your desired configuration options:
void main() {
runApp(
SuravApp(
checkerboardOffscreenLayers: false,
debugShowCheckedModeBanner: false,
navigatorObservers: [],
routes: {},
showPerformanceOverlay: false,
showSemanticsDebugger: false,
checkerboardRasterCacheImages: false,
debugShowMaterialGrid: false,
supportedLocales: [Locale('en', 'US')],
themeMode: ThemeMode.system,
title: "My App",
),
);
}
You can customize various properties such as theme, actions, builder, home, initialRoute, and more to suit your application's specific needs.
Creating an ApiRequest
To create an instance of the ApiRequest class, you need to provide the URL and optional parameters such as method, body, options, and others.
ApiRequest request = ApiRequest(
'https://example.com/api/endpoint',
method: ApiMethod.POST,
body: {'key': 'value'},
showLogs: true, // Set to false to disable logging
);
Sending Requests
To send a request, use the send method. This method returns a Future<Response>.
Response response = await request.send();
Handling Responses
The send method returns a Dio Response object. You can handle the response as needed:
if (response.statusCode == 200) {
// Handle success
print(response.data);
} else {
// Handle error
print('Request failed with status: ${response.statusCode}');
}
Logging
Logging is handled by the Logger package. The logging behavior depends on the request method and whether logging is enabled.
- GET requests: Informational logs
- POST and DELETE requests: Warning logs
- Other methods: Fatal logs
Logs include stack traces for better debugging.
SuravLocal Class
The SuravLocal class provides methods for managing local data storage using the shared_preferences package.
Setting Data
To set a value in local storage, use one of the following methods:
await SuravLocal.setString('key', 'value');
await SuravLocal.setBool('key', true);
await SuravLocal.setInt('key', 123);
await SuravLocal.setDouble('key', 123.45);
await SuravLocal.setStringList('key', ['value1', 'value2']);
Getting Data
To retrieve a value from local storage, use one of the following methods:
String? stringValue = await SuravLocal.getString('key');
bool? boolValue = await SuravLocal.getBool('key');
int? intValue = await SuravLocal.getInt('key');
double? doubleValue = await SuravLocal.getDouble('key');
List<String>? stringListValue = await SuravLocal.getStringList('key');
Clearing Data
To remove a specific value or clear all data from local storage, use the following methods:
await SuravLocal.remove('key');
await SuravLocal.clear();
Additional Functions
packFormData
The packFormData function helps in packing data into a FormData object for multipart/form-data requests.
FormData formData = packFormData({
'name': 'John Doe',
'file': await addFormFile('/path/to/file'),
});
addFormFile
The addFormFile function helps in adding a file to the FormData.
MultipartFile file = await addFormFile('/path/to/file', filename: 'file.txt');
String Extensions
capitalize
Capitalizes the first letter of each word in a string.
String text = "hello world".capitalize();
// Output: "Hello World"
getFileName
Extracts the file name from a file path.
String fileName = "/path/to/file.txt".getFileName();
// Output: "file.txt"
getTruncatedFilenameWithDots
Truncates a file name to a maximum length of 22 characters, adding ".." if truncated.
String truncatedFileName = "/path/to/very_long_file_name.txt".getTruncatedFilenameWithDots();
// Output: "very_long_file_na..txt"
getFileExtension
Extracts the file extension from a file path.
String fileExtension = "/path/to/file.txt".getFileExtension();
// Output: "txt"
formatDate
Formats a date string in "YYYY-MM-DDTHH:MM:SS" format to "DD Mon YYYY".
String formattedDate = "2023-12-25T00:00:00".formatDate();
// Output: "25 Dec 2023"
lastCharacters
Gets the last n characters of a string.
String lastChars = "hello world".lastCharacters(5);
// Output: "world"
firstCharacters
Gets the first n characters of a string, followed by "...".
String firstChars = "hello world".firstCharacters(5);
// Output: "hello..."
Numeric Extensions
toMinutes
Converts seconds to minutes, rounded to 3 decimal places.
double minutes = 120.toMinutes();
// Output: 2.000
Validation Extensions
isValidEmail
Validates if a string is a valid email format.
bool isEmail = "example@example.com".isValidEmail();
// Output: true
isValidPhoneNumber
Validates if a string is a valid phone number format.
bool isPhoneNumber = "+1-123-456-7890".isValidPhoneNumber();
// Output: true
BuildContext Extensions
windowWidth
Gets the width of the window.
double width = context.windowWidth;
windowHeight
Gets the height of the window.
double height = context.windowHeight;
Toast Utility
showToast
Displays a toast message on the screen.
void showToast(
String msg, {
Toast toastLength = Toast.LENGTH_SHORT,
ToastGravity gravity = ToastGravity.BOTTOM,
int timeInSecForIosWeb = 1,
Color backgroundColor = Colors.black,
Color textColor = Colors.white,
double fontSize = 16.0,
}) {
Fluttertoast.cancel();
Fluttertoast.showToast(
msg: msg,
toastLength: toastLength,
gravity: gravity,
timeInSecForIosWeb: timeInSecForIosWeb,
backgroundColor: backgroundColor,
textColor: textColor,
fontSize: fontSize,
);
}
Example
Here's a complete example demonstrating how to use
ElevatedButton(
onPressed: () => showToast('This is a toast message'),
child: Text('Show Toast'),
),
Introduction
The SuravNavigate class provides global keys for managing navigation and snackbars within a Flutter application. It simplifies the process of navigating between screens and displaying snackbars from anywhere in the application.
Initialization
First, you need to initialize the SuravNavigate class in your MaterialApp widget. This ensures that the global keys are properly set up for managing navigation and snackbars.
import 'package:flutter/material.dart';
import 'surav_navigate.dart'; // Ensure this file includes the provided SuravNavigate class
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: SuravNavigate.navigateKey,
scaffoldMessengerKey: SuravNavigate.snackbarKey,
home: HomeScreen(),
);
}
}
Navigation
To navigate to a new screen, you can use the navigate global instance. This allows you to perform navigation operations from anywhere in your code.
NavigatorState navigate = SuravNavigate.navigateKey.currentState!;
void navigateToScreen(Widget screen) {
navigate.push(routeMe(screen));
}
Showing Snackbars
To show a snackbar, you can use the snackbarKey to get the current ScaffoldMessengerState.
void showSnackbar(String message) {
SuravNavigate.snackbarKey.currentState!.showSnackBar(
SnackBar(content: Text(message)),
);
}
Utility Function
The routeMe function is a utility that creates a MaterialPageRoute for a given screen.
MaterialPageRoute routeMe(Widget screen) {
return MaterialPageRoute(builder: (context) {
return screen;
});
}
Example
Here's a complete example demonstrating how to use the SuravNavigate class and its related utilities in a Flutter application:
import 'package:flutter/material.dart';
import 'surav_navigate.dart'; // Ensure this file includes the provided SuravNavigate class
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: SuravNavigate.navigateKey,
scaffoldMessengerKey: SuravNavigate.snackbarKey,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home Screen')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
navigateToScreen(SecondScreen());
},
child: Text('Navigate to Second Screen'),
),
ElevatedButton(
onPressed: () {
showSnackbar('This is a snackbar message');
},
child: Text('Show Snackbar'),
),
],
),
),
);
}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Second Screen')),
body: Center(
child: ElevatedButton(
onPressed: () {
navigate.pop();
},
child: Text('Go Back'),
),
),
);
}
}
void navigateToScreen(Widget screen) {
NavigatorState navigate = SuravNavigate.navigateKey.currentState!;
navigate.push(routeMe(screen));
}
void showSnackbar(String message) {
SuravNavigate.snackbarKey.currentState!.showSnackBar(
SnackBar(content: Text(message)),
);
}
Make sure to save the provided SuravNavigate class in a file (e.g., surav_navigate.dart) and import it in your main file as shown in the example. This will enable you to utilize the navigation and snackbar functionalities across your Flutter application.
Sure, let's organize the code:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:surav/surav.dart';
class SuravProvider {
static T use<T>({bool listen = false}) {
return Provider.of<T>(currentContext, listen: listen);
}
}
Here's the sorted version:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:surav/surav.dart';
class SuravProvider {
static T use<T>({bool listen = false}) {
return Provider.of<T>(currentContext, listen: listen);
}
}
It's a minor change, but maintaining a consistent structure can make the code easier to read and maintain.
Shimmer
import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
import 'path_to_your_surav_shimmer_widget.dart'; // Update this import statement to the correct path of your SuravShimmer widget file
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shimmer Example',
home: ShimmerExample(),
);
}
}
class ShimmerExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Shimmer Example'),
),
body: Center(
child: SuravShimmer(
width: 200,
height: 100,
radius: 10,
baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!,
child: Container(
color: Colors.grey[300],
),
),
),
);
}
}
Explanation
SuravShimmer Widget:
- The
SuravShimmerwidget is configured with a width of 200, height of 100, and a border radius of 10. baseColorandhighlightColorare set to provide the shimmer effect.- A
Containerwith a grey background is used as the child, which will display the shimmer effect.
SuravImage
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'path_to_your_surav_image_widget.dart'; // Update this import statement to the correct path of your SuravImage widget file
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Surav Image Example',
home: ImageExample(),
);
}
}
class ImageExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Surav Image Example'),
),
body: Center(
child: SuravImage(
url: 'https://example.com/image.jpg',
width: 200,
height: 200,
fadeInDuration: Duration(milliseconds: 1000),
fadeOutDuration: Duration(milliseconds: 500),
placeholderFadeInDuration: Duration(milliseconds: 500),
),
),
);
}
}
Explanation
SuravImage Widget:
- The
SuravImagewidget is configured with a URL, width, and height. - Additional optional properties such as
fadeInDuration,fadeOutDuration, andplaceholderFadeInDurationare provided to customize the animation timings.