commonkit 0.1.3
commonkit: ^0.1.3 copied to clipboard
A lightweight utility package for Flutter with widgets, helpers, and extensions
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:commonkit/commonkit.dart';
import 'dart:io' if (dart.library.io) 'dart:io';
import 'package:image_picker/image_picker.dart' if (dart.library.io) 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart' if (dart.library.io) 'package:permission_handler/permission_handler.dart';
/// Initializes the app with necessary setup and runs the [CommonKitExampleApp].
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (!kIsWeb) {
await StorageHelper.init();
}
GlobalConfig().init(
baseUrl: 'https://jsonplaceholder.typicode.com',
variables: {'apiKey': '12345'},
isDebugMode: true,
theme: const CommonKitTheme(primaryColor: Colors.blue),
);
runApp(const CommonKitExampleApp());
}
/// A simple example application demonstrating the features of the `commonkit` package.
///
/// This app showcases various utilities and widgets provided by `commonkit`, including
/// network requests, file uploads, directory management, clipboard operations, and
/// permission handling. It is designed to work on both mobile/desktop and web platforms,
/// with WASM compatibility handled through conditional logic.
///
/// Example usage:
/// ```dart
/// void main() {
/// runApp(const CommonKitExampleApp());
/// }
/// ```
class CommonKitExampleApp extends StatelessWidget {
const CommonKitExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const ExamplePage(),
theme: ThemeData(primarySwatch: Colors.blue),
);
}
}
/// A page demonstrating key features of the `commonkit` package.
///
/// Includes examples for:
/// - Network requests using [NetworkHelper].
/// - File uploads with [NetworkHelper] and [ImagePicker] (non-web only).
/// - Directory management using [DirectoryManager] (non-web only).
/// - Clipboard operations with [ClipboardManager].
/// - Permission handling with [PermissionManager] (non-web only).
///
/// This page is fully compatible with web (WASM) by disabling non-supported features
/// with appropriate user feedback.
class ExamplePage extends StatefulWidget {
const ExamplePage({super.key});
@override
State<ExamplePage> createState() => _ExamplePageState();
}
class _ExamplePageState extends State<ExamplePage> {
final _networkHelper = NetworkHelper();
final _directoryManager = DirectoryManager();
final _sessionManager = SessionManager();
String _status = '';
/// Tests a network request using [NetworkHelper].
///
/// Fetches a sample post from a placeholder API and displays its title.
Future<void> _testNetwork() async {
try {
setState(() => _status = 'Fetching...');
final data = await _networkHelper.get('/posts/1');
setState(() => _status = 'Network: ${data['title'].truncate(20)}');
Logger.info('Network test succeeded');
showToast(context, message: 'Network Success');
} catch (e) {
setState(() => _status = 'Network Error: $e');
Logger.error('Network test failed', e);
showCustomDialog(context, title: 'Error', content: e.toString());
}
}
/// Tests file upload functionality with [NetworkHelper] and [ImagePicker].
///
/// Picks an image from the gallery and attempts to upload it. Disabled on web.
Future<void> _testFileUpload() async {
if (!kIsWeb) {
final picker = ImagePicker();
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
setState(() => _status = 'Uploading...');
final file = File(pickedFile.path);
try {
final data = await _networkHelper.post(
'/upload',
body: {'title': 'Example Upload'},
files: [file],
);
setState(() => _status = 'Upload: $data');
Logger.info('File upload succeeded: $data');
showToast(context, message: 'Upload Success');
} catch (e) {
setState(() => _status = 'Upload Error: $e');
Logger.error('File upload failed', e);
showToast(context, message: 'Upload Error: $e');
}
}
} else {
setState(() => _status = 'File upload not supported on web');
showToast(context, message: 'Feature unavailable on WASM');
}
}
/// Tests directory management using [DirectoryManager].
///
/// Creates a directory and a test file within it. Disabled on web.
Future<void> _testDirectory() async {
if (!kIsWeb) {
setState(() => _status = 'Creating directory...');
try {
final dir = await _directoryManager.createDirectory('example_dir');
await _directoryManager.createFile('example_dir/test.txt', content: 'Example');
setState(() => _status = 'Directory: ${dir.path}');
Logger.info('Directory test succeeded: ${dir.path}');
showToast(context, message: 'Directory Created');
} catch (e) {
setState(() => _status = 'Directory Error: $e');
Logger.error('Directory test failed', e);
showToast(context, message: 'Directory Error: $e');
}
} else {
setState(() => _status = 'Directory management not supported on web');
showToast(context, message: 'Feature unavailable on WASM');
}
}
/// Tests clipboard operations with [ClipboardManager].
///
/// Copies a sample text and pastes it back to verify functionality.
Future<void> _testClipboard() async {
try {
await ClipboardManager.copy('Example Text');
final pasted = await ClipboardManager.paste();
setState(() => _status = 'Clipboard: $pasted');
Logger.info('Clipboard test succeeded: $pasted');
showToast(context, message: 'Copied and Pasted');
} catch (e) {
setState(() => _status = 'Clipboard Error: $e');
Logger.error('Clipboard test failed', e);
showToast(context, message: 'Clipboard Error: $e');
}
}
/// Tests permission handling with [PermissionManager].
///
/// Requests storage permission and shows the result. Disabled on web.
Future<void> _testPermission() async {
if (!kIsWeb) {
try {
final granted = await PermissionManager.request(Permission.storage);
setState(() => _status = 'Permission: ${granted ? "Granted" : "Denied"}');
Logger.info('Permission test: ${granted ? "Granted" : "Denied"}');
showCustomDialog(
context,
title: 'Permission',
content: granted ? 'Storage granted' : 'Storage denied',
negativeText: granted ? null : 'Settings',
onNegative: granted ? null : () => PermissionManager.openSettings(),
);
} catch (e) {
setState(() => _status = 'Permission Error: $e');
Logger.error('Permission test failed', e);
showToast(context, message: 'Permission Error: $e');
}
} else {
setState(() => _status = 'Permissions not supported on web');
showToast(context, message: 'Feature unavailable on WASM');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('CommonKit Examples'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Add to _ExamplePageState.build in Column children
CustomButton(
text: 'Test Image Picker',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(title: const Text('Image Picker Test')),
body: AdvancedImagePicker(
onImagePicked: (image) => setState(() => _status = 'Image: $image'),
),
),
),
);
},
icon: Icons.image,
),
const Text('Try out CommonKit features:', style: TextStyle(fontSize: 18)),
const SizedBox(height: 16),
CustomButton(
text: 'Test Network Request',
onPressed: _testNetwork,
icon: Icons.network_check,
),
const SizedBox(height: 16),
CustomButton(
text: 'Test File Upload',
onPressed: _testFileUpload,
icon: Icons.upload_file,
isDisabled: kIsWeb, // Disable on web
),
const SizedBox(height: 16),
CustomButton(
text: 'Test Directory Management',
onPressed: _testDirectory,
icon: Icons.folder,
isDisabled: kIsWeb, // Disable on web
),
const SizedBox(height: 16),
CustomButton(
text: 'Test Clipboard',
onPressed: _testClipboard,
icon: Icons.copy,
),
const SizedBox(height: 16),
CustomButton(
text: 'Test Permission',
onPressed: _testPermission,
icon: Icons.security,
isDisabled: kIsWeb, // Disable on web
),
const SizedBox(height: 16),
Text('Status: $_status', style: const TextStyle(fontSize: 16)),
],
),
),
);
}
}
const bool kIsWeb = identical(0, 0.0);