### Example Package Entry (Markdown)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/CONTRIBUTING.md
Provides a complete example of how a package entry should be formatted in a Markdown file, including the package name, a brief description, and an embedded image using HTML.
```markdown
auto_size_text
Flutter widget that automatically resizes text to fit perfectly within its bounds.
```
--------------------------------
### Example Localization JSON (Rosetta)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Example JSON file defining localization keys and their corresponding English values. This file serves as input for the Rosetta code generator.
```JSON
{
"hello_there": "Hello there!",
"see_you_soon": "See you soon!"
}
```
--------------------------------
### Getting Package Info with package_info (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to use the package_info plugin to retrieve information about the application package. It shows how to get the app name, package name, version, and build number.
```Dart
import 'package:package_info/package_info.dart';
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;
```
--------------------------------
### Getting Device Information using device_info Plugin in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Device/device_info.md
This snippet demonstrates how to use the device_info plugin to get detailed information about the device. It initializes the plugin, retrieves platform-specific info (Android or iOS), and prints key details like the model or machine name. Requires the 'device_info' package dependency.
```Dart
import 'package:device_info/device_info.dart';
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print('Running on ${androidInfo.model}'); // e.g. "Moto G (4)"
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
print('Running on ${iosInfo.utsname.machine}'); // e.g. "iPod7,1"
```
--------------------------------
### Basic Set/Get Operations with mmkv_flutter (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Persistance/mmkv_flutter.md
This snippet shows how to initialize the mmkv_flutter plugin and perform basic operations like setting and getting boolean and string values. It retrieves an instance, sets a boolean, prints it, retrieves a string, appends '1' to it, prints the modified string, and saves it back.
```dart
MmkvFlutter mmkv = await MmkvFlutter.getInstance();
mmkv.setBool('boolKey', true);
print('get bool value is ${ await mmkv.getBool('boolKey')}');
String stringtest = await mmkv.getString('stringKey') + '1';
print('GetSetStringTest value is $stringtest');
await mmkv.setString('stringKey', stringtest);
```
--------------------------------
### Starting NFC Tag Reading Session (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This function demonstrates how to initiate an NFC tag reading session using the `flutter_nfc_reader` plugin. It calls `FlutterNfcReader.read` to start pooling for a tag and handles potential `PlatformException` errors. The function returns a `Future` containing `NfcData` if a tag is read. Requires the `flutter_nfc_reader` package dependency.
```Dart
Future startNFC() async {
NfcData response;
try {
response = await FlutterNfcReader.read;
} on PlatformException {
//Something went wrong
}
return response;
}
```
--------------------------------
### Performing HTTP GET Request with Dio (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet illustrates how to make an HTTP GET request using the `dio` package. It uses an `async` function and `await` to perform the request and handle the response or any errors. The `Dio` client is instantiated, and the `get` method is called with the target URL.
```Dart
import 'package:dio/dio.dart';
void getHttp() async {
try {
Response response = await Dio().get("http://www.google.com");
return print(response);
} catch (e) {
return print(e);
}
}
```
--------------------------------
### Example Rosetta Localization JSON File
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Utils/rosetta.md
This JSON snippet shows the structure of a localization file used by the rosetta library. It contains key-value pairs where keys are used in the Dart code to retrieve localized strings.
```json
{
"hello_there": "Hello there!",
"see_you_soon": "See you soon!"
}
```
--------------------------------
### Using MMKV for Key-Value Storage with mmkv_flutter (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Demonstrates basic usage of the mmkv_flutter plugin for high-performance key-value storage. It shows how to get an instance, set and retrieve a boolean value, and retrieve, modify, and set a string value.
```Dart
MmkvFlutter mmkv = await MmkvFlutter.getInstance();
mmkv.setBool('boolKey', true);
print('get bool value is ${ await mmkv.getBool('boolKey')}');
String stringtest = await mmkv.getString('stringKey') + '1';
print('GetSetStringTest value is $stringtest');
await mmkv.setString('stringKey', stringtest);
```
--------------------------------
### Sharing Content with share (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to use the share plugin to share content via the platform's native share UI. It shows a simple example of sharing a text string and a URL.
```Dart
import 'package:share/share.dart';
Share.share('check out my website https://example.com');
```
--------------------------------
### Making a GET Request with Dio in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Networking/dio.md
This asynchronous function demonstrates how to use the Dio package to perform a simple HTTP GET request to a specified URL. It handles both successful responses and potential errors during the request.
```Dart
import 'package:dio/dio.dart';
void getHttp() async {
try {
Response response = await Dio().get("http://www.google.com");
return print(response);
} catch (e) {
return print(e);
}
}
```
--------------------------------
### Enqueueing and Managing Downloads with Flutter Downloader (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet shows how to use the `flutter_downloader` plugin to enqueue a background download task and register a callback to monitor its progress and status. The `enqueue` method starts the download, specifying the URL, save directory, and notification options. The `registerCallback` function allows updating the UI or performing actions based on the download state changes.
```Dart
final taskId = await FlutterDownloader.enqueue(
url: 'your download link',
savedDir: 'the path of directory where you want to save downloaded files',
showNotification: true, // show download progress in status bar (for Android)
openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);
FlutterDownloader.registerCallback((id, status, progress) {
// code to update your UI
});
```
--------------------------------
### Implementing a HookWidget with Animation Controller in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Frameworks & Design Patterns/flutter_hooks.md
This snippet defines a simple Flutter HookWidget named 'Example'. It takes a 'duration' parameter and uses the 'useAnimationController' hook within its build method to create an AnimationController instance tied to the widget's lifecycle. The widget currently returns an empty Container.
```Dart
class Example extends HookWidget {
final Duration duration;
const Example({@required this.duration});
@override
Widget build(BuildContext context) {
final controller = useAnimationController(duration: duration);
return Container();
}
}
```
--------------------------------
### Building Form with flutter_form_builder in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Demonstrates how to construct a Material form using the FormBuilder widget. It includes examples of adding text and password input fields with basic validation and handling form changes and submission. Requires the 'flutter_form_builder' package.
```dart
FormBuilder(
context,
autovalidate: true,
controls: [
FormBuilderInput.textField(
type: FormBuilderInput.TYPE_TEXT,
attribute: "name",
label: "Name",
require: true,
min: 3,
),
FormBuilderInput.password(
attribute: "password",
label: "Password",
//require: true,
),
],
onChanged: () {
print("Form Changed");
},
onSubmit: (formValue) {
if (formValue != null) {
print(formValue);
} else {
print("Form invalid");
}
},
),
```
--------------------------------
### Compressing Image File in Flutter
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Provides an example of using the `flutter_image_compress` package to compress an image file. It shows how to specify the input file path, desired minimum width and height, quality, and rotation. The function returns the compressed image data.
```Dart
var result = await FlutterImageCompress.compressWithFile(
file.absolute.path,
minWidth: 2300,
minHeight: 1500,
quality: 94,
rotate: 90,
);
```
--------------------------------
### Accessing Temporary and Document Directories (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Files/path_provider.md
This snippet demonstrates how to use the path_provider package to asynchronously retrieve the temporary directory and the application documents directory. It shows how to get the Directory objects and extract their file paths.
```Dart
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
```
--------------------------------
### Getting Directory Paths with path_provider in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to use the `path_provider` package to obtain standard directory paths on the device filesystem, such as the temporary directory and the application's documents directory. It requires the `path_provider` package.
```Dart
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
```
--------------------------------
### Getting Device Info with device_info (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet illustrates how to use the device_info plugin to get detailed information about the device the app is running on. It shows how to differentiate between Android and iOS and access platform-specific details like model or machine name.
```Dart
import 'package:device_info/device_info.dart';
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print('Running on ${androidInfo.model}'); // e.g. "Moto G (4)"
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
print('Running on ${iosInfo.utsname.machine}'); // e.g. "iPod7,1"
```
--------------------------------
### Defining a MobX Store in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Provides an example of defining a MobX store in Dart. It shows the use of the `part` directive for code generation, the base class and mixin (`_Counter with _$Counter`), and the `@observable` and `@action` annotations for defining reactive state and state-modifying methods.
```Dart
part 'counter.g.dart';
class Counter = _Counter with _$Counter;
abstract class _Counter implements Store {
@observable
int value = 0;
@action
void increment() {
value++;
}
}
```
--------------------------------
### Getting Current Location with geolocator (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet shows how to use the geolocator plugin to get the device's current geographical position. It demonstrates requesting the position with a specified accuracy.
```Dart
import 'package:geolocator/geolocator.dart';
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
```
--------------------------------
### Controlling Screen Settings with screen (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to use the screen plugin to manage device screen settings. It shows how to get and set screen brightness, check if the screen is kept on, and prevent the screen from going to sleep.
```Dart
import 'package:screen/screen.dart';
// Get the current brightness:
double brightness = await Screen.brightness;
// Set the brightness:
Screen.setBrightness(0.5);
// Check if the screen is kept on:
bool isKeptOn = await Screen.isKeptOn;
// Prevent screen from going into sleep mode:
Screen.keepOn(true);
```
--------------------------------
### Starting NFC Reading Session (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Bluetooth & Wifi/flutter_nfc_reader.md
This function initiates an NFC reading session using the FlutterNfcReader plugin. It attempts to read an NFC tag and returns the data. It includes basic error handling for PlatformException.
```Dart
Future startNFC() async {
NfcData response;
try {
response = await FlutterNfcReader.read;
} on PlatformException {
//Something went wrong
}
return response;
}
```
--------------------------------
### Managing Contacts with contacts_service (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet illustrates how to use the contacts_service plugin to interact with the device's contact list. It shows examples of retrieving all contacts, querying contacts by string, adding a new contact, and deleting a contact.
```Dart
import 'package:contacts_service/contacts_service.dart';
// Get all contacts
Iterable contacts = await ContactsService.getContacts();
// Get contacts matching a string
Iterable johns = await ContactsService.getContacts(query : "john");
await ContactsService.addContact(newContact);
await ContactsService.deleteContact(contact);
```
--------------------------------
### Reading HTTP Content with http Package (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet shows how to perform a simple HTTP GET request using the `http` package to read the content of a URL. It imports the package with an alias `http` and uses the `read` function, which returns a `Future` that completes with the body of the response. The `.then(print)` part handles the Future's result by printing it.
```Dart
import 'package:http/http.dart' as http;
http.read("http://example.com/foobar.txt").then(print);
```
--------------------------------
### Building UI Based on Connectivity Status (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This example uses the `OfflineBuilder` widget from the `flutter_offline` package to dynamically build UI based on the network connectivity status. The `connectivityBuilder` callback receives the current `ConnectivityResult` and returns a widget (here, a Text widget showing "online" or "offline"). Requires the `flutter_offline` package dependency.
```Dart
OfflineBuilder(
connectivityBuilder: (
BuildContext context,
ConnectivityResult connectivity,
Widget child,
) {
final bool connected = connectivity != ConnectivityResult.none;
return Text(connected ? "online" : "offline");
},
);
```
--------------------------------
### Using a MobX Store in a Flutter Widget
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Frameworks & Design Patterns/flutter_mobx.md
This Flutter widget example demonstrates how to instantiate and use the "Counter" MobX store. It utilizes the "Observer" widget from "flutter_mobx" to automatically rebuild the UI when the observable "_counter.value" changes, and a button to trigger the "increment" action.
```Dart
class CounterExample extends StatefulWidget {
@override
_CounterExampleState createState() => _CounterExampleState();
}
class _CounterExampleState extends State {
final _counter = Counter();
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Observer(
builder: (_) => Text('${_counter.value}'),
),
Button(
onPressed: _counter.increment,
child: const Icon(Icons.add),
)
],
);
}
}
```
--------------------------------
### Getting Current Position using Geolocator in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Device/geolocator.md
Imports the geolocator package and retrieves the device's current geographical position with high accuracy. Requires the 'geolocator' dependency added to your pubspec.yaml file.
```Dart
import 'package:geolocator/geolocator.dart';
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
```
--------------------------------
### Performing Basic Data Operations with sembast in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Persistance/sembast.md
This snippet illustrates fundamental database interactions with sembast, including storing data using `put`, retrieving data using `get`, and removing data using `delete`. It shows how to handle different data types like strings, integers, and maps.
```Dart
await db.put('Simple application', 'title');
await db.put(10, 'version');
await db.put({'offline': true}, 'settings');
// read values
String title = await db.get('title') as String;
int version = await db.get('version') as int;
Map settings = await db.get('settings') as Map;
// ...and delete
await db.delete('version');
```
--------------------------------
### Storing and Retrieving Data with sembast (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Illustrates basic data manipulation using the sembast NoSQL database. It shows how to store different data types (string, int, map) using the `put` method, retrieve them using `get` with type casting, and delete a key-value pair using `delete`.
```Dart
await db.put('Simple application', 'title');
await db.put(10, 'version');
await db.put({'offline': true}, 'settings');
// read values
String title = await db.get('title') as String;
int version = await db.get('version') as int;
Map settings = await db.get('settings') as Map;
// ...and delete
await db.delete('version');
```
--------------------------------
### Implementing Scoped Model with Counter Example (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Frameworks & Design Patterns/scoped_model.md
This snippet demonstrates the basic usage of `scoped_model`. It defines a `CounterModel` that extends `Model` and uses `notifyListeners()` to signal changes. The `CounterApp` widget uses `ScopedModel` to provide the model and `ScopedModelDescendant` to access the model and rebuild when it changes.
```Dart
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
_counter++; // First, increment the counter
notifyListeners(); // Then notify all the listeners.
}
}
class CounterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Create a `ScopedModel` widget. This will provide the `model` to the children that request it.
return ScopedModel(
model: CounterModel(),
child: Column(children: [
// Create a ScopedModelDescendant. This widget will get the CounterModel from the nearest
// ScopedModel. It will rebuild any time the CounterModel changes
ScopedModelDescendant(
builder: (context, child, model) => Text('${model.counter}'),
),
Text("Another widget that doesn't depend on the CounterModel")
]),
);
}
}
```
--------------------------------
### Validating Email Address using email_validator in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Shows a simple example of using the EmailValidator class to check if a given string is a valid email address. The validate method returns a boolean indicating the validity. Requires the 'email_validator' package.
```dart
var email = "fredrik@gmail.com";
assert(EmailValidator.validate(email) == true);
```
--------------------------------
### Incrementing Counter using SharedPreferences in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Persistance/shared_preferences.md
This asynchronous function demonstrates how to retrieve an integer value ('counter') from shared preferences, increment it, print the updated value, and save it back. It uses `SharedPreferences.getInstance()` to get the preferences instance and handles the case where the key might not exist initially.
```Dart
incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = (prefs.getInt('counter') ?? 0) + 1;
print('Pressed $counter times.');
await prefs.setInt('counter', counter);
}
```
--------------------------------
### Accessing Battery Info with battery Plugin (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to use the `battery` plugin to get the current battery level and listen for changes in the battery state (charging, discharging, full). It requires importing the `battery` package. The `batteryLevel` property provides the current percentage, and the `onBatteryStateChanged` stream allows reacting to state changes.
```Dart
import 'package:battery/battery';
var battery = Battery();
print(battery.batteryLevel); // Access current battery level
// Be informed when the state (full, charging, discharging) changes
_battery.onBatteryStateChanged.listen((BatteryState state) {
// Do something with new state
});
```
--------------------------------
### Defining Serializable Class with json_serializable in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Utils/json_serializable.md
This snippet defines a `Person` class using annotations from the `json_annotation` package. The `@JsonSerializable` annotation marks the class for code generation. The `part 'example.g.dart';` directive is necessary for the generated code to be included. The factory constructor `fromJson` and the `toJson` method are standard patterns used with `json_serializable`, relying on the generated `_$` functions.
```Dart
import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';
@JsonSerializable(nullable: false)
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map json) => _$PersonFromJson(json);
Map toJson() => _$PersonToJson(this);
}
```
--------------------------------
### Linking Images in Package Entry (HTML)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/CONTRIBUTING.md
Demonstrates how to embed an image within a package entry using standard HTML, specifying the image source path and display width.
```html
```
--------------------------------
### Retrieving Package Information using package_info in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Device/package_info.md
This snippet demonstrates how to use the `package_info` plugin to retrieve application details. It imports the necessary package, asynchronously fetches the `PackageInfo` object using `PackageInfo.fromPlatform()`, and then accesses properties like `appName`, `packageName`, `version`, and `buildNumber`.
```Dart
import 'package:package_info/package_info.dart';
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;
```
--------------------------------
### Integrating MobX Store into a Flutter Widget
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Begins the implementation of a Flutter StatefulWidget (`CounterExample`) that instantiates a MobX store (`_counter`) in its state. This snippet sets up the basic structure for a Flutter widget that will likely use an `Observer` widget (not shown) to react to changes in the MobX store.
```Dart
class CounterExample extends StatefulWidget {
@override
_CounterExampleState createState() => _CounterExampleState();
}
class _CounterExampleState extends State {
final _counter = Counter();
@override
Widget build(BuildContext context) {
return Column(
```
--------------------------------
### Basic Audio Playback Controls (audioplayer/Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Illustrates the fundamental operations for controlling audio playback using the `audioplayer` plugin, including creating an instance and calling `play`, `pause`, and `stop` methods.
```dart
AudioPlayer audioPlugin = new AudioPlayer();
audioPlayer.play(kUrl);
audioPlayer.pause();
audioPlayer.stop();
```
--------------------------------
### Initializing and Inserting Data into ObjectDB in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Initializes an ObjectDB instance with a file path and opens the database connection. It then demonstrates inserting a sample document containing nested objects, strings, booleans, and numbers into the database.
```dart
db = ObjectDB(File(dbFilePath));
db.open();
// insert sample data
db.insert({
'name': {'first': 'Alex', 'last': 'Boyle'},
'message': 'abc',
'active': true,
'count': 0,
});
```
--------------------------------
### Launching URLs with url_launcher Plugin (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to use the `url_launcher` plugin to open a URL. It first checks if the URL can be launched using `canLaunch` and then launches it using `launch`. This plugin supports various URL schemes like web, phone, SMS, and email on both Android and iOS.
```Dart
import 'package:url_launcher/url_launcher.dart';
const url = 'https://flutter.io';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
```
--------------------------------
### Reading HTTP Content (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Networking/http.md
Demonstrates how to use the `http.read` function to fetch the content of a URL as a string and print it. Requires the `http` package dependency.
```Dart
import 'package:http/http.dart' as http;
http.read("http://example.com/foobar.txt").then(print);
```
--------------------------------
### Launching a URL using url_launcher in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Networking/url_launcher.md
This snippet demonstrates how to use the url_launcher package to open a web URL. It first checks if the URL can be launched using `canLaunch` and then launches it using `launch`. If launching fails, it throws an error.
```Dart
import 'package:url_launcher/url_launcher.dart';
const url = 'https://flutter.io';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
```
--------------------------------
### Loading, Resizing, and Saving Image File in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Shows how to use the `image` package to load an image from a file, resize it while maintaining aspect ratio, and then save the modified image to a new file in a different format (PNG). Requires `dart:io` for file operations.
```Dart
Image image = decodeImage(Io.File('test.webp').readAsBytesSync());
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
Image thumbnail = copyResize(image, 120);
// Save the thumbnail as a PNG.
Io.File('thumbnail.png')
..writeAsBytesSync(encodePng(thumbnail));
```
--------------------------------
### Managing Cookies with cookie_jar (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Shows how to use the cookie_jar package for managing HTTP cookies. It demonstrates creating a list of Cookie objects, initializing a CookieJar instance, saving cookies received from a response URI, and loading cookies required for a request URI.
```Dart
import 'package:cookie_jar/cookie_jar.dart';
void main() async {
List cookies = [new Cookie("name", "wendux"), new Cookie("location", "china")];
var cj = new CookieJar();
//Save cookies
cj.saveFromResponse(Uri.parse("https://www.baidu.com/"), cookies);
//Get cookies
List results = cj.loadForRequest(Uri.parse("https://www.baidu.com/xx"));
print(results);
}
```
--------------------------------
### Using Superpower List Extensions (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Demonstrates how to use the Superpower library to wrap a standard Dart List and access extended functionalities like sum(), negative indexing ([-1]), and slicing (slice(-2)).
```Dart
var superList = $([0, 10, 100, 1000]);
var sum = superList.sum(); // 1110
var last = superList[-1]; // 1000
var lastTwo = superList.slice(-2); // [100, 1000]
```
--------------------------------
### Building a Counter Widget with State Management (Flutter/Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Demonstrates a Flutter widget structure for a counter, displaying a value from a state object and providing a button to increment it. The use of `Observer` suggests integration with a reactive state management solution.
```dart
mainAxisAlignment: MainAxisAlignment.center,
children: [
Observer(
builder: (_) => Text('${_counter.value}'),
),
Button(
onPressed: _counter.increment,
child: const Icon(Icons.add),
)
],
);
}
}
```
--------------------------------
### Creating Platform-Adaptive Alert Dialog with PlatformAlertDialog (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Widgets/flutter_platform_widgets.md
Illustrates the creation of a platform-adaptive alert dialog using `PlatformAlertDialog`. It allows specifying a title, content, and a list of actions.
```Dart
PlatformAlertDialog(
title: Text('Alert'),
content: Text('Some content'),
actions: [
PlatformDialogAction(),
PlatformDialogAction(),
],
);
```
--------------------------------
### Initializing FormBuilder with Fields - Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Input & Forms/flutter_form_builder.md
This snippet demonstrates how to create a FormBuilder widget, configure autovalidation, define form controls like TextField and Password with validation rules (require, min), and set up onChanged and onSubmit callbacks to handle form state changes and submission.
```Dart
FormBuilder(
context,
autovalidate: true,
controls: [
FormBuilderInput.textField(
type: FormBuilderInput.TYPE_TEXT,
attribute: "name",
label: "Name",
require: true,
min: 3,
),
FormBuilderInput.password(
attribute: "password",
label: "Password",
//require: true,
),
],
onChanged: () {
print("Form Changed");
},
onSubmit: (formValue) {
if (formValue != null) {
print(formValue);
} else {
print("Form invalid");
}
},
),
```
--------------------------------
### Opening a File with open_file in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet shows how to use the `open_file` package to open a specified file using the device's native applications. It requires importing the `open_file` package.
```Dart
import 'package:open_file/open_file;
OpenFile.open("/sdcard/example.txt");
```
--------------------------------
### Basic Audio Playback with audioplayer in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Audio & Video/audioplayer.md
This snippet demonstrates the basic usage of the `AudioPlayer` plugin in Dart. It shows how to initialize the player, play an audio file from a URL, pause playback, and stop playback.
```Dart
AudioPlayer audioPlugin = new AudioPlayer();
audioPlayer.play(kUrl);
audioPlayer.pause();
audioPlayer.stop();
```
--------------------------------
### Registering App and Sharing Text with fluwx
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Utils/fluwx.md
This snippet demonstrates how to initialize the fluwx package by registering your application with a specific WeChat App ID and then sharing a simple text message to a WeChat session using the WeChatShareTextModel.
```Dart
import 'package:fluwx/fluwx.dart' as fluwx;
fluwx.register(appId:"wxd930ea5d5a258f4f");
fluwx.share(
WeChatShareTextModel(
text: "text from fluwx",
transaction: "transaction",
scene: WeChatScene.SESSION,
),
);
```
--------------------------------
### Using CookieJar for Saving and Loading Cookies in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Persistance/cookie_jar.md
This snippet demonstrates how to initialize a CookieJar, create a list of Cookie objects, save them associated with a specific URI, and then load cookies for another URI. It requires the 'cookie_jar' package dependency.
```Dart
import 'package:cookie_jar/cookie_jar.dart';
void main() async {
List cookies = [new Cookie("name", "wendux"), new Cookie("location", "china")];
var cj = new CookieJar();
//Save cookies
cj.saveFromResponse(Uri.parse("https://www.baidu.com/"), cookies);
//Get cookies
List results = cj.loadForRequest(Uri.parse("https://www.baidu.com/xx"));
print(results);
}
```
--------------------------------
### Executing Code After First Layout in Flutter/Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Utils/after_layout.md
Demonstrates how to use the AfterLayoutMixin in a Flutter StatefulWidget to execute code, such as showing a dialog, immediately after the widget's first frame has been rendered. This is achieved by implementing the afterFirstLayout method.
```Dart
class HomeScreen extends StatefulWidget {
@override
HomeScreenState createState() => new HomeScreenState();
}
class HomeScreenState extends State with AfterLayoutMixin {
@override
Widget build(BuildContext context) {
return new Scaffold(body: new Container(color: Colors.red));
}
@override
void afterFirstLayout(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text('Hello World'),
),
);
}
}
```
--------------------------------
### Performing Basic List Operations with Superpower (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Utils/superpower.md
This snippet demonstrates how to use the 'superpower' package to enhance a standard Dart List. It shows how to wrap a list using the $(...) constructor, calculate the sum of elements, access elements from the end using negative indices, and extract a sublist using the slice method with a negative index.
```Dart
var superList = $([0, 10, 100, 1000]);
var sum = superList.sum(); // 1110
var last = superList[-1]; // 1000
var lastTwo = superList.slice(-2); // [100, 1000]
```
--------------------------------
### Initializing and Inserting Data into ObjectDB (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Persistance/objectdb_flutter.md
This snippet shows how to create an instance of ObjectDB linked to a file, open the database connection, and insert a sample document containing various data types including nested objects.
```Dart
db = ObjectDB(File(dbFilePath));
db.open();
// insert sample data
db.insert({
'name': {'first': 'Alex', 'last': 'Boyle'},
'message': 'abc',
'active': true,
'count': 0,
});
```
--------------------------------
### Implementing ScopedModel State Management in Flutter
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Demonstrates how to use the `scoped_model` package in Flutter. It defines a `Model` subclass (`CounterModel`) to hold state and logic, and a `StatelessWidget` (`CounterApp`) that uses `ScopedModel` to provide the model and `ScopedModelDescendant` to consume it and rebuild the UI when the model changes.
```Dart
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
_counter++; // First, increment the counter
notifyListeners(); // Then notify all the listeners.
}
}
class CounterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Create a `ScopedModel` widget. This will provide the `model` to the children that request it.
return ScopedModel(
model: CounterModel(),
child: Column(children: [
// Create a ScopedModelDescendant. This widget will get the CounterModel from the nearest
// ScopedModel. It will rebuild any time the CounterModel changes
ScopedModelDescendant(
builder: (context, child, model) => Text('${model.counter}'),
),
Text("Another widget that doesn't depend on the CounterModel")
]),
);
}
}
```
--------------------------------
### Configuring and Listening to Logging Records in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Configures the root logger's level to ALL to capture all log messages. It then sets up a listener on the root logger's record stream to print the log level, time, and message to the console for every incoming log record.
```dart
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((LogRecord rec) {
print('${rec.level.name}: ${rec.time}: ${rec.message}');
});
```
--------------------------------
### Registering and Sharing with Fluwx WeChatSDK - Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet shows how to initialize the fluwx plugin by registering with an App ID and then demonstrates sharing a text message to a WeChat session using the share method with a WeChatShareTextModel.
```Dart
import 'package:fluwx/fluwx.dart' as fluwx;
fluwx.register(appId:"wxd930ea5d5a258f4f");
fluwx.share(
WeChatShareTextModel(
text: "text from fluwx",
transaction: "transaction",
scene: WeChatScene.SESSION,
),
);
```
--------------------------------
### Displaying Advanced Network Image in Flutter
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Illustrates how to use the `AdvancedNetworkImage` provider with the standard `Image` widget. It demonstrates setting custom headers, enabling disk caching, and defining a cache rule with a maximum age.
```Dart
Image(
image: AdvancedNetworkImage(
url,
header: header,
useDiskCache: true,
cacheRule: CacheRule(maxAge: const Duration(days: 7)),
),
fit: BoxFit.cover,
)
```
--------------------------------
### Using useAnimationController Hook (Flutter Hooks/Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Shows how to define a `HookWidget` and utilize the `useAnimationController` hook within the build method to manage an animation controller's lifecycle based on a specified duration.
```dart
class Example extends HookWidget {
final Duration duration;
const Example({@required this.duration});
@override
Widget build(BuildContext context) {
final controller = useAnimationController(duration: duration);
return Container();
}
}
```
--------------------------------
### Opening a File using open_file Plugin in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Files/open_file.md
This snippet demonstrates how to use the `open_file` plugin to open a file on the device's native file system. It requires importing the `open_file` package. The `OpenFile.open()` method is called with the file path as an argument.
```Dart
import 'package:open_file/open_file.dart';
OpenFile.open("/sdcard/example.txt");
```
--------------------------------
### Compressing Image File with Flutter Image Compress (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Images/flutter_image_compress.md
This snippet demonstrates how to compress an image file using the `compressWithFile` method. It takes the file path and compression options like minimum width, height, quality, and rotation.
```Dart
var result = await FlutterImageCompress.compressWithFile(
file.absolute.path,
minWidth: 2300,
minHeight: 1500,
quality: 94,
rotate: 90,
);
```
--------------------------------
### Creating and Rendering a SpriteComponent in Flame (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Animations/flame.md
This snippet demonstrates how to create a `SpriteComponent` in Flame using a `Sprite` loaded from an image file. It shows how to initialize the component with size and sprite, and how to set its position and angle. Finally, it illustrates how to render the component onto a canvas.
```Dart
import 'package:flame/components/component.dart';
Sprite sprite = new Sprite('player.png');
const size = 128.0;
final player = new SpriteComponent.fromSprite(size, size, sprite); // width, height, sprite
player.x = ... // 0 by default
player.y = ... // 0 by default
player.angle = ... // 0 by default
// on your render method...
player.render(canvas);
```
--------------------------------
### Creating Platform-Adaptive Alert Dialog in Flutter
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Illustrates the usage of PlatformAlertDialog to create a dialog that automatically uses the appropriate native style (Material or Cupertino) for alerts, including title, content, and actions. Requires the flutter_platform_widgets package.
```Dart
PlatformAlertDialog(
title: Text('Alert'),
content: Text('Some content'),
actions: [
PlatformDialogAction(),
PlatformDialogAction(),
],
);
```
--------------------------------
### Detecting Konami Code with RxDart - Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet uses RxDart to listen for keyboard events, map key codes, buffer the last 10 codes, filter for the Konami sequence, and react when the sequence is matched, demonstrating stream processing for event handling.
```Dart
const konamiKeyCodes = const [
KeyCode.UP, KeyCode.UP,
KeyCode.DOWN, KeyCode.DOWN,
KeyCode.LEFT, KeyCode.RIGHT,
KeyCode.LEFT, KeyCode.RIGHT,
KeyCode.B, KeyCode.A
];
final result = querySelector('#result');
final keyUp = new Observable(document.onKeyUp);
keyUp
.map((event) => event.keyCode)
.bufferCount(10, 1)
.where((lastTenKeyCodes) => const IterableEquality().equals(lastTenKeyCodes, konamiKeyCodes))
.listen((_) => result.innerHtml = 'KONAMI!');
```
--------------------------------
### Load, Resize, and Save Image with Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Images/image.md
This snippet demonstrates how to load an image from a file, resize it to a thumbnail while maintaining its aspect ratio, and then save the modified image to a new file in a different format. It uses functions from the 'image' library for decoding, resizing, and encoding.
```Dart
Image image = decodeImage(Io.File('test.webp').readAsBytesSync());
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
Image thumbnail = copyResize(image, 120);
// Save the thumbnail as a PNG.
Io.File('thumbnail.png')
..writeAsBytesSync(encodePng(thumbnail));
```
--------------------------------
### Creating Platform-Adaptive Button with PlatformButton (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Widgets/flutter_platform_widgets.md
Shows how to create a platform-adaptive button using `PlatformButton`. It includes an `onPressed` callback and a `child` widget for the button's content.
```Dart
PlatformButton(
onPressed: () => print('send'),
child: PlatformText('Send'),
);
```
--------------------------------
### Creating Platform-Adaptive Widget in Flutter
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Demonstrates how to use PlatformWidget to conditionally render different icons based on the platform (iOS or Android), simplifying cross-platform UI development. Requires the flutter_platform_widgets package.
```Dart
PlatformWidget(
ios: (_) => Icon(CupertinoIcons.flag),
android: (_) => Icon(Icons.flag),
);
```
--------------------------------
### Creating Platform-Adaptive Icon with PlatformWidget (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Widgets/flutter_platform_widgets.md
Demonstrates how to use `PlatformWidget` to display different icons based on the platform (iOS or Android). It takes builder functions for each platform.
```Dart
PlatformWidget(
ios: (_) => Icon(CupertinoIcons.flag),
android: (_) => Icon(Icons.flag),
);
```
--------------------------------
### Enqueueing a Download Task in Flutter Downloader (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Networking/flutter_downloader.md
This snippet demonstrates how to initiate a background download task using the FlutterDownloader.enqueue method. It requires the download URL, a directory to save the file, and options for showing notifications on Android. It returns a unique task ID.
```Dart
final taskId = await FlutterDownloader.enqueue(
url: 'your download link',
savedDir: 'the path of directory where you want to save downloaded files',
showNotification: true, // show download progress in status bar (for Android)
openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);
```
--------------------------------
### Creating Platform-Adaptive Button in Flutter
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
Shows how to use PlatformButton and PlatformText to create a button that adapts its appearance to the native platform (Material on Android, Cupertino on iOS), handling the press event. Requires the flutter_platform_widgets package.
```Dart
PlatformButton(
onPressed: () => print('send'),
child: PlatformText('Send'),
);
```
--------------------------------
### Setting up Rosetta Translation Class in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Utils/rosetta.md
This Dart code defines the main `Translation` class for the rosetta library. It uses the `@Stone` annotation to specify the path to localization files and includes static members for the `LocalizationsDelegate` and a helper method to access translations from the context.
```dart
part 'translation.g.dart';
@Stone(path: 'i18n')
class Translation with _$TranslationHelper {
static LocalizationsDelegate delegate = _$TranslationDelegate();
static Translation of(BuildContext context) {
return Localizations.of(context, Translation);
}
}
```
--------------------------------
### Creating and Accessing Tuple Elements - Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet illustrates how to create a Tuple2 instance with two elements of different types and how to access these elements using the item1 and item2 properties.
```Dart
var t = const Tuple2('a', 10);
print(t.item1); // prints 'a'
print(t.item2); // prints '10'
```
--------------------------------
### Executing Code After First Layout - Flutter/Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates using the AfterLayoutMixin with a StatefulWidget to implement the afterFirstLayout method, which is called once after the widget's first frame has been rendered, useful for showing dialogs or performing actions that depend on layout information.
```Dart
class HomeScreen extends StatefulWidget {
@override
HomeScreenState createState() => new HomeScreenState();
}
class HomeScreenState extends State with AfterLayoutMixin {
@override
Widget build(BuildContext context) {
return new Scaffold(body: new Container(color: Colors.red));
}
@override
void afterFirstLayout(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text('Hello World'),
),
);
}
}
```
--------------------------------
### Configuring Root Logger - Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Logging & Error Handling/logging.md
This snippet demonstrates how to configure the root logger to capture all log levels and print log records to the console. It sets the root logger's level to ALL and adds a listener to the onRecord stream to process incoming log records.
```Dart
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((LogRecord rec) {
print('${rec.level.name}: ${rec.time}: ${rec.message}');
});
```
--------------------------------
### Creating a SpriteComponent in Flame (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to create a SpriteComponent using the Flame game engine in Dart. It involves importing the necessary component class, loading a sprite from an asset, instantiating the SpriteComponent with a specified size and the loaded sprite, and shows how to set its position and rotation. It also briefly mentions rendering the component on a canvas.
```Dart
import 'package:flame/components/component.dart';
Sprite sprite = new Sprite('player.png');
const size = 128.0;
final player = new SpriteComponent.fromSprite(size, size, sprite); // width, height, sprite
player.x = ... // 0 by default
player.y = ... // 0 by default
player.angle = ... // 0 by default
// on your render method...
player.render(canvas);
```
--------------------------------
### Accessing Battery Information in Flutter (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Device/battery.md
This snippet demonstrates how to initialize the 'battery' plugin, retrieve the current battery level, and set up a listener for changes in the battery state (e.g., charging, discharging). It requires the 'battery' plugin dependency.
```Dart
import 'package:battery/battery.dart';
var battery = Battery();
print(battery.batteryLevel); // Access current battery level
// Be informed when the state (full, charging, discharging) changes
_battery.onBatteryStateChanged.listen((BatteryState state) {
// Do something with new state
});
```
--------------------------------
### Managing Contacts with contacts_service Plugin (Dart)
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Device/contacts_service.md
This snippet demonstrates common operations using the contacts_service Flutter plugin. It shows how to retrieve all contacts, query contacts by name, add a new contact, and delete an existing contact.
```Dart
import 'package:contacts_service/contacts_service.dart';
// Get all contacts
Iterable contacts = await ContactsService.getContacts();
// Get contacts matching a string
Iterable johns = await ContactsService.getContacts(query : "john");
await ContactsService.addContact(newContact);
await ContactsService.deleteContact(contact);
```
--------------------------------
### Defining Fluro Route Handler and Registration - Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/README.md
This snippet demonstrates how to create a Handler function to process a route and then register that handler with the Router instance for a specific path, including a named parameter :id.
```Dart
var usersHandler = Handler(handlerFunc: (BuildContext context, Map params) {
return UsersScreen(params["id"][0]);
});
final router = Router();
router.define("/users/:id", handler: usersHandler);
```
--------------------------------
### Detecting Konami Code with RxDart in Dart
Source: https://github.com/simc/awesome-flutter-packages/blob/master/packages/Utils/rxdart.md
This snippet uses RxDart streams to listen for keyboard key up events. It maps the events to key codes, buffers the last 10 codes, filters the stream to only pass sequences matching the Konami Code, and updates an HTML element when the sequence is detected. Requires 'dart:html' for DOM access and 'package:collection' for Iterable comparison.
```Dart
const konamiKeyCodes = const [
KeyCode.UP, KeyCode.UP,
KeyCode.DOWN, KeyCode.DOWN,
KeyCode.LEFT, KeyCode.RIGHT,
KeyCode.LEFT, KeyCode.RIGHT,
KeyCode.B, KeyCode.A
];
final result = querySelector('#result');
final keyUp = new Observable(document.onKeyUp);
keyUp
.map((event) => event.keyCode)
.bufferCount(10, 1)
.where((lastTenKeyCodes) => const IterableEquality().equals(lastTenKeyCodes, konamiKeyCodes))
.listen((_) => result.innerHtml = 'KONAMI!');
```