Commonly Used Dart Packages
Dart has a rich ecosystem of packages that can help developers build applications more efficiently. These packages provide pre-built functionality, allowing you to avoid reinventing the wheel. Below are some commonly used Dart packages along with their descriptions and sample code demonstrating their usage.
1. http
The http
package is used for making HTTP requests. It simplifies the process of sending and receiving data over the web, making it easy to interact with RESTful APIs.
Example of Using the http Package
import 'package:http/http.dart' as http;
void main() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
print('Response data: ${response.body}');
} else {
print('Request failed with status: ${response.statusCode}');
}
}
In this example, we import the http
package and use it to make a GET request to a sample API. We check the response status and print the response data if the request is successful.
2. provider
The provider
package is a popular state management solution for Flutter applications. It allows you to manage and share state across your app efficiently.
Example of Using the provider Package
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Provider Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: ${context.watch<counter>().count}'),
ElevatedButton(
onPressed: () => context.read<counter>().increment(),
child: Text('Increment'),
),
],
),
),
),
);
}
}
</counter></counter>
In this example, we create a simple counter application using the provider
package. The Counter
class extends ChangeNotifier
to notify listeners when the count changes. We use ChangeNotifierProvider
to provide the Counter
instance to the widget tree.
3. shared_preferences
The shared_preferences
package is used for storing simple data persistently on the device. It is commonly used for saving user preferences and settings.
Example of Using the shared_preferences Package
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PreferenceExample(),
);
}
}
class PreferenceExample extends StatefulWidget {
@override
_PreferenceExampleState createState() => _PreferenceExampleState();
}
class _PreferenceExampleState extends State<preferenceexample> {
String _savedValue = '';
@override
void initState() {
super.initState();
_loadSavedValue();
}
_loadSavedValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_savedValue = prefs.getString('my_key') ?? '';
});
}
_saveValue(String value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('my_key', value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Shared Preferences Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Saved Value: $_savedValue'),
TextField(
onSubmitted: (value) {
_saveValue(value);
_loadSavedValue();
},
decoration: InputDecoration(labelText: 'Enter a value'),
),
],
),
),
);
}
}
</preferenceexample>
In this example, we use the shared_preferences
package to save and retrieve a simple string value. The application allows the user to enter a value, which is then saved persistently using shared preferences. When the app is restarted, the saved value is loaded and displayed.
4. dio
The dio
package is a powerful HTTP client for Dart that supports interceptors, global configuration, form data, request cancellation, and more. It is particularly useful for complex HTTP requests.
Example of Using the dio Package
import 'package:dio/dio.dart';
void main() async {
final dio = Dio();
try {
final response = await dio.get('https://jsonplaceholder.typicode.com/posts');
print('Response data: ${response.data}');
} catch (e) {
print('Error: $e');
}
}
In this example, we create an instance of Dio
and use it to make a GET request. The response data is printed to the console, and any errors are caught and displayed.
5. flutter_local_notifications
The flutter_local_notifications
package is used for displaying local notifications in Flutter applications. It allows you to schedule notifications and customize their appearance.
Example of Using the flutter_local_notifications Package
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: NotificationExample(),
);
}
}
class NotificationExample extends StatefulWidget {
@override
_NotificationExampleState createState() => _NotificationExampleState();
}
class _NotificationExampleState extends State<notificationexample> {
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
@override
void initState() {
super.initState();
_initializeNotifications();
}
void _initializeNotifications() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final InitializationSettings initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
Future<void> _showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('your_channel_id', 'your_channel_name',
channelDescription: 'your_channel_description',
importance: Importance.max,
priority: Priority.high);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.show(0, 'Hello', 'This is a local notification', platformChannelSpecifics);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Local Notifications Example')),
body: Center(
child: ElevatedButton(
onPressed: _showNotification,
child: Text('Show Notification'),
),
),
);
}
}
</void></notificationexample>
In this example, we set up local notifications using the flutter_local_notifications
package. When the button is pressed, a local notification is displayed with a title and message.
Conclusion
These are just a few of the commonly used Dart packages that can enhance your development experience. By leveraging these packages, you can save time and effort while building robust applications. Explore the Dart package repository at pub.dev to discover more packages that suit your needs.