Gordon  Matlala

Gordon Matlala

1679317505

Powertoys: Windows System Utilities To Maximize Productivity

Microsoft PowerToys

Hero image for Microsoft PowerToys

About

Microsoft PowerToys is a set of utilities for power users to tune and streamline their Windows experience for greater productivity. For more info on PowerToys overviews and how to use the utilities, or any other tools and resources for Windows development environments, head over to learn.microsoft.com!

 Current utilities: 
Always on TopPowerToys AwakeColor Picker
FancyZonesFile Explorer Add-onsFile Locksmith
Hosts File EditorImage ResizerKeyboard Manager
Mouse utilitiesPaste as Plain TextPowerRename
PowerToys RunQuick AccentScreen Ruler
Shortcut GuideText ExtractorVideo Conference Mute

Installing and running Microsoft PowerToys

Requirements

  • Windows 11 or Windows 10 version 2004 (code name 20H1 / build number 19041) or newer.
  • Our installer will install the following items:

Via GitHub with EXE [Recommended]

Go to Microsoft PowerToys GitHub releases page, click on Assets at the bottom to show the files available in the release. Please use the appropriate PowerToys installer that matches your machine's architecture. For most, it is x64.

This is our preferred method.

Via Microsoft Store

Install from the Microsoft Store's PowerToys page. You must be using the new Microsoft Store which is available for both Windows 11 and Windows 10.

Via WinGet

Download PowerToys from WinGet. To install PowerToys, run the following command from the command line / PowerShell:

winget install Microsoft.PowerToys -s winget

Other install methods

There are community driven install methods such as Chocolatey and Scoop. If these are your preferred install solutions, you can find the install instructions there.

Contributing

This project welcomes contributions of all types. Help spec'ing, design, documentation, finding bugs are ways everyone can help on top of coding features / bug fixes. We are excited to work with the power user community to build a set of tools for helping you get the most out of Windows.

We ask that before you start work on a feature that you would like to contribute, please read our Contributor's Guide. We will be happy to work with you to figure out the best approach, provide guidance and mentorship throughout feature development, and help avoid any wasted or duplicate effort.

Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.

For guidance on developing for PowerToys, please read the developer docs for a detailed breakdown. This includes how to setup your computer to compile.

What's Happening

PowerToys Roadmap

Our prioritized roadmap of features and utilities that the core team is focusing on.

0.68 - February 2023 Update

In this release, we focused on releasing new features, stability and improvements.

Highlights

  • New utility: Paste as Plain Text allows pasting the text contents of your clipboard without formatting. Note: the formatted text in the clipboard is replaced with the unformatted text. Thanks @carlos-zamora!
  • New utility: Mouse Jump allows to quickly move the mouse pointer long distances on a single screen or across multiple screens. Thanks @mikeclayton!
  • Add new GPO policies for automatic update downloads and update toast notifications. Thanks @htcfreek!
  • Support MSC and CPL files in "Run command" results of PowerToys Run Program plugin. Thanks @htcfreek!
  • Add support for log2 and log10 in PowerToys Run Calculator plugin. Thanks @RickLuiken!
  • Added experimentation to PowerToys first run experience. There are current page which says "welcome" and a variant with direct instructions on how to use some of the utilities. We want to see if directly showing how to use PowerToys leads to more people using the features :)

General

  • Improve metered network detection in runner. Thanks @davidegiacometti!
  • Update PowerToys logo used by installer. Thanks @ChaseKnowlden!
  • Add new GPO policies for automatic update downloads and update toast notifications. Thanks @htcfreek!
  • Update copyright year to 2023. Thanks @ChaseKnowlden!

FancyZones

  • Refactored and improved code quality.
  • Fix crashing on moving window between monitors with Win + arrows. (This was a hotfix for 0.67)
  • Fix issue causing window attributes to not be reset properly. (This was a hotfix for 0.67)
  • Fix issue causing window to not be adjusted when layout is changed. (This was a hotfix for 0.67)
  • Fix issue causing window not to be unsnapped on drag started. (This was a hotfix for 0.67)
  • Fix issue causing layouts not to be applied to new virtual desktops. (This was a hotfix for 0.67)
  • Fix issues causing windows not to be restored correctly to their last known zone.

File explorer add-ons

  • Add Developer files previewer option to set max file size and fix styling issue. Thanks @Aaron-Junker!
  • Improve Developer files previewer exception handling and printing of error messages.
  • Fix crash when generating PDF and Gcode file thumbnails. (This was a hotfix for 0.67)

Hosts file editor

Keyboard Manager

Mouse Utils

  • Resolve grammatical error in Mouse Highlighter description. Thanks @WordlessSafe1!
  • New utility: Mouse Jump allows to quickly move the mouse pointer long distances on single or across screens. Thanks @mikeclayton!

Paste as Plain Text

  • New utility: Paste as Plain Text allows pasting the text contents of your clipboard without formatting. Note: the formatted text in the clipboard is replaced with the unformatted text. Thanks @carlos-zamora!

PowerToys Run

  • Show Steam (steam://open/) shortcuts in the Program plugin.
  • Localize paths of Program plugin results. Thanks @htcfreek!
  • Improved stability of the code used to get the localized names and paths. Thanks @htcfreek!
  • Support MSC and CPL files in "Run command" results of Program plugin. Thanks @htcfreek!
  • Added missing MSC and CPL settings to the results of Windows Settings plugin. Thanks @htcfreek!
  • System plugin: Setting for separate "Open/Empty Recycle bin" results or single result with context menu. (This was implemented based on user feedback for a change in the last build.) Thanks @htcfreek!
  • Add support for log2 and log10 in Calculator plugin. Thanks @RickLuiken!
  • Removed the TimeZone plugin.
  • Fix the crash when loading thumbnail for PDF files. (This was a hotfix for 0.67)

Shortcut Guide

Quick Accent

Settings

  • Add missing flyout borders on Windows 10. Thanks @davidegiacometti!
  • Add experimentation for oobe landing page. Thanks @chenss3!
  • Show icons of user-installed PowerToys Run plugins. Thanks @al2me6!
  • Fixed crash when clicking Browse for backup and restore location while running elevated.
  • Respect taskbar position when showing system tray flyout. (This was a hotfix for 0.67)
  • Show correct Hosts module image. (This was a hotfix for 0.67)

Development

  • Turned on C++ code analysis and incrementally fixing warnings.
  • Centralize .NET NuGet packages versions. Thanks @snickler!
  • Separate PowerToys installer logs and MSI logs to different files.
  • Added new GPO rules to the reporting tool.
  • Move PowerToys registry entries back to HKLM to fix context menu entries not working on some configurations. (This was a hotfix for 0.67)

What is being planned for version 0.69

For v0.69, we'll work on below:

  • Allow installing without UAC.
  • New utility: PowerToys Peek
  • Stability / bug fixes

PowerToys Community

The PowerToys team is extremely grateful to have the support of an amazing active community. The work you do is incredibly important. PowerToys wouldn’t be nearly what it is today without your help filing bugs, updating documentation, guiding the design, or writing features. We want to say thank you and take time to recognize your work. Month over month, you directly help make PowerToys a better piece of software.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct.

Privacy Statement

The application logs basic telemetry. Our Telemetry Data page (Coming Soon) has the trends from the telemetry. Please read the Microsoft privacy statement for more information.


Build status

ArchitectureSolution (Main)Solution (Stable)Installer (Main)
x64Build Status for MainBuild Status for StableBuild Status Installer pipeline
ARM64Build Status for MainBuild Status for MainBuild Status Installer pipeline

Download Details:

Author: Microsoft
Source Code: https://github.com/microsoft/PowerToys 
License: MIT license

#csharp #windows #color #picker #desktop #keyboard #managed 

Powertoys: Windows System Utilities To Maximize Productivity

Image Picker plugin for Flutter

 

Image Picker plugin for Flutter

A Flutter plugin for iOS and Android for picking images from the image library, and taking new pictures with the camera.

 AndroidiOSWeb
SupportSDK 21+iOS 11+See image_picker_for_web

Installation

First, add image_picker as a dependency in your pubspec.yaml file.

iOS

Starting with version 0.8.1 the iOS implementation uses PHPicker to pick (multiple) images on iOS 14 or higher. As a result of implementing PHPicker it becomes impossible to pick HEIC images on the iOS simulator in iOS 14+. This is a known issue. Please test this on a real device, or test with non-HEIC images until Apple solves this issue. 63426347 - Apple known issue

Add the following keys to your Info.plist file, located in <project root>/ios/Runner/Info.plist:

  • NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
    • This permission will not be requested if you always pass false for requestFullMetadata, but App Store policy requires including the plist entry.
  • NSCameraUsageDescription - describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
  • NSMicrophoneUsageDescription - describe why your app needs access to the microphone, if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor.

Android

Starting with version 0.8.1 the Android implementation support to pick (multiple) images on Android 4.3 or higher.

No configuration required - the plugin should work out of the box. It is however highly recommended to prepare for Android killing the application when low on memory. How to prepare for this is discussed in the Handling MainActivity destruction on Android section.

It is no longer required to add android:requestLegacyExternalStorage="true" as an attribute to the <application> tag in AndroidManifest.xml, as image_picker has been updated to make use of scoped storage.

Note: Images and videos picked using the camera are saved to your application's local cache, and should therefore be expected to only be around temporarily. If you require your picked image to be stored permanently, it is your responsibility to move it to a more permanent location.

Example

import 'package:image_picker/image_picker.dart';

    ...
    final ImagePicker _picker = ImagePicker();
    // Pick an image
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    // Capture a photo
    final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
    // Pick a video
    final XFile? image = await _picker.pickVideo(source: ImageSource.gallery);
    // Capture a video
    final XFile? video = await _picker.pickVideo(source: ImageSource.camera);
    // Pick multiple images
    final List<XFile>? images = await _picker.pickMultiImage();
    ...

Handling MainActivity destruction on Android

When under high memory pressure the Android system may kill the MainActivity of the application using the image_picker. On Android the image_picker makes use of the default Intent.ACTION_GET_CONTENT or MediaStore.ACTION_IMAGE_CAPTURE intents. This means that while the intent is executing the source application is moved to the background and becomes eligable for cleanup when the system is low on memory. When the intent finishes executing, Android will restart the application. Since the data is never returned to the original call use the ImagePicker.retrieveLostData() method to retrieve the lost data. For example:

Future<void> getLostData() async {
  final LostDataResponse response =
      await picker.retrieveLostData();
  if (response.isEmpty) {
    return;
  }
  if (response.files != null) {
    for (final XFile file in response.files) {
      _handleFile(file);
    }
  } else {
    _handleError(response.exception);
  }
}

This check should always be run at startup in order to detect and handle this case. Please refer to the example app for a more complete example of handling this flow.

Android Photo Picker

This package has optional Android Photo Picker functionality. Learn how to use it.

Migrating to 0.8.2+

Starting with version 0.8.2 of the image_picker plugin, new methods have been added for picking files that return XFile instances (from the cross_file package) rather than the plugin's own PickedFile instances. While the previous methods still exist, it is already recommended to start migrating over to their new equivalents. Eventually, PickedFile and the methods that return instances of it will be deprecated and removed.

Call the new methods

Old APINew API
PickedFile image = await _picker.getImage(...)XFile image = await _picker.pickImage(...)
List<PickedFile> images = await _picker.getMultiImage(...)List<XFile> images = await _picker.pickMultiImage(...)
PickedFile video = await _picker.getVideo(...)XFile video = await _picker.pickVideo(...)
LostData response = await _picker.getLostData()LostDataResponse response = await _picker.retrieveLostData()

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add image_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  image_picker: ^0.8.7

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:image_picker/image_picker.dart'; 

example/lib/main.dart

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Image Picker Demo',
      home: MyHomePage(title: 'Image Picker Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, this.title});

  final String? title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<XFile>? _imageFileList;

  void _setImageFileListFromFile(XFile? value) {
    _imageFileList = value == null ? null : <XFile>[value];
  }

  dynamic _pickImageError;
  bool isVideo = false;

  VideoPlayerController? _controller;
  VideoPlayerController? _toBeDisposed;
  String? _retrieveDataError;

  final ImagePicker _picker = ImagePicker();
  final TextEditingController maxWidthController = TextEditingController();
  final TextEditingController maxHeightController = TextEditingController();
  final TextEditingController qualityController = TextEditingController();

  Future<void> _playVideo(XFile? file) async {
    if (file != null && mounted) {
      await _disposeVideoController();
      late VideoPlayerController controller;
      if (kIsWeb) {
        controller = VideoPlayerController.network(file.path);
      } else {
        controller = VideoPlayerController.file(File(file.path));
      }
      _controller = controller;
      // In web, most browsers won't honor a programmatic call to .play
      // if the video has a sound track (and is not muted).
      // Mute the video so it auto-plays in web!
      // This is not needed if the call to .play is the result of user
      // interaction (clicking on a "play" button, for example).
      const double volume = kIsWeb ? 0.0 : 1.0;
      await controller.setVolume(volume);
      await controller.initialize();
      await controller.setLooping(true);
      await controller.play();
      setState(() {});
    }
  }

  Future<void> _onImageButtonPressed(ImageSource source,
      {BuildContext? context, bool isMultiImage = false}) async {
    if (_controller != null) {
      await _controller!.setVolume(0.0);
    }
    if (isVideo) {
      final XFile? file = await _picker.pickVideo(
          source: source, maxDuration: const Duration(seconds: 10));
      await _playVideo(file);
    } else if (isMultiImage) {
      await _displayPickImageDialog(context!,
          (double? maxWidth, double? maxHeight, int? quality) async {
        try {
          final List<XFile> pickedFileList = await _picker.pickMultiImage(
            maxWidth: maxWidth,
            maxHeight: maxHeight,
            imageQuality: quality,
          );
          setState(() {
            _imageFileList = pickedFileList;
          });
        } catch (e) {
          setState(() {
            _pickImageError = e;
          });
        }
      });
    } else {
      await _displayPickImageDialog(context!,
          (double? maxWidth, double? maxHeight, int? quality) async {
        try {
          final XFile? pickedFile = await _picker.pickImage(
            source: source,
            maxWidth: maxWidth,
            maxHeight: maxHeight,
            imageQuality: quality,
          );
          setState(() {
            _setImageFileListFromFile(pickedFile);
          });
        } catch (e) {
          setState(() {
            _pickImageError = e;
          });
        }
      });
    }
  }

  @override
  void deactivate() {
    if (_controller != null) {
      _controller!.setVolume(0.0);
      _controller!.pause();
    }
    super.deactivate();
  }

  @override
  void dispose() {
    _disposeVideoController();
    maxWidthController.dispose();
    maxHeightController.dispose();
    qualityController.dispose();
    super.dispose();
  }

  Future<void> _disposeVideoController() async {
    if (_toBeDisposed != null) {
      await _toBeDisposed!.dispose();
    }
    _toBeDisposed = _controller;
    _controller = null;
  }

  Widget _previewVideo() {
    final Text? retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_controller == null) {
      return const Text(
        'You have not yet picked a video',
        textAlign: TextAlign.center,
      );
    }
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: AspectRatioVideo(_controller),
    );
  }

  Widget _previewImages() {
    final Text? retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_imageFileList != null) {
      return Semantics(
        label: 'image_picker_example_picked_images',
        child: ListView.builder(
          key: UniqueKey(),
          itemBuilder: (BuildContext context, int index) {
            // Why network for web?
            // See https://pub.dev/packages/image_picker#getting-ready-for-the-web-platform
            return Semantics(
              label: 'image_picker_example_picked_image',
              child: kIsWeb
                  ? Image.network(_imageFileList![index].path)
                  : Image.file(File(_imageFileList![index].path)),
            );
          },
          itemCount: _imageFileList!.length,
        ),
      );
    } else if (_pickImageError != null) {
      return Text(
        'Pick image error: $_pickImageError',
        textAlign: TextAlign.center,
      );
    } else {
      return const Text(
        'You have not yet picked an image.',
        textAlign: TextAlign.center,
      );
    }
  }

  Widget _handlePreview() {
    if (isVideo) {
      return _previewVideo();
    } else {
      return _previewImages();
    }
  }

  Future<void> retrieveLostData() async {
    final LostDataResponse response = await _picker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      if (response.type == RetrieveType.video) {
        isVideo = true;
        await _playVideo(response.file);
      } else {
        isVideo = false;
        setState(() {
          if (response.files == null) {
            _setImageFileListFromFile(response.file);
          } else {
            _imageFileList = response.files;
          }
        });
      }
    } else {
      _retrieveDataError = response.exception!.code;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title!),
      ),
      body: Center(
        child: !kIsWeb && defaultTargetPlatform == TargetPlatform.android
            ? FutureBuilder<void>(
                future: retrieveLostData(),
                builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                    case ConnectionState.waiting:
                      return const Text(
                        'You have not yet picked an image.',
                        textAlign: TextAlign.center,
                      );
                    case ConnectionState.done:
                      return _handlePreview();
                    case ConnectionState.active:
                      if (snapshot.hasError) {
                        return Text(
                          'Pick image/video error: ${snapshot.error}}',
                          textAlign: TextAlign.center,
                        );
                      } else {
                        return const Text(
                          'You have not yet picked an image.',
                          textAlign: TextAlign.center,
                        );
                      }
                  }
                },
              )
            : _handlePreview(),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Semantics(
            label: 'image_picker_example_from_gallery',
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(ImageSource.gallery, context: context);
              },
              heroTag: 'image0',
              tooltip: 'Pick Image from gallery',
              child: const Icon(Icons.photo),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(
                  ImageSource.gallery,
                  context: context,
                  isMultiImage: true,
                );
              },
              heroTag: 'image1',
              tooltip: 'Pick Multiple Image from gallery',
              child: const Icon(Icons.photo_library),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(ImageSource.camera, context: context);
              },
              heroTag: 'image2',
              tooltip: 'Take a Photo',
              child: const Icon(Icons.camera_alt),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.gallery);
              },
              heroTag: 'video0',
              tooltip: 'Pick Video from gallery',
              child: const Icon(Icons.video_library),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.camera);
              },
              heroTag: 'video1',
              tooltip: 'Take a Video',
              child: const Icon(Icons.videocam),
            ),
          ),
        ],
      ),
    );
  }

  Text? _getRetrieveErrorWidget() {
    if (_retrieveDataError != null) {
      final Text result = Text(_retrieveDataError!);
      _retrieveDataError = null;
      return result;
    }
    return null;
  }

  Future<void> _displayPickImageDialog(
      BuildContext context, OnPickImageCallback onPick) async {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('Add optional parameters'),
            content: Column(
              children: <Widget>[
                TextField(
                  controller: maxWidthController,
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  decoration: const InputDecoration(
                      hintText: 'Enter maxWidth if desired'),
                ),
                TextField(
                  controller: maxHeightController,
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                  decoration: const InputDecoration(
                      hintText: 'Enter maxHeight if desired'),
                ),
                TextField(
                  controller: qualityController,
                  keyboardType: TextInputType.number,
                  decoration: const InputDecoration(
                      hintText: 'Enter quality if desired'),
                ),
              ],
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('CANCEL'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              TextButton(
                  child: const Text('PICK'),
                  onPressed: () {
                    final double? width = maxWidthController.text.isNotEmpty
                        ? double.parse(maxWidthController.text)
                        : null;
                    final double? height = maxHeightController.text.isNotEmpty
                        ? double.parse(maxHeightController.text)
                        : null;
                    final int? quality = qualityController.text.isNotEmpty
                        ? int.parse(qualityController.text)
                        : null;
                    onPick(width, height, quality);
                    Navigator.of(context).pop();
                  }),
            ],
          );
        });
  }
}

typedef OnPickImageCallback = void Function(
    double? maxWidth, double? maxHeight, int? quality);

class AspectRatioVideo extends StatefulWidget {
  const AspectRatioVideo(this.controller, {super.key});

  final VideoPlayerController? controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController? get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller!.value.isInitialized) {
      initialized = controller!.value.isInitialized;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    controller!.addListener(_onVideoControllerUpdate);
  }

  @override
  void dispose() {
    controller!.removeListener(_onVideoControllerUpdate);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller!.value.aspectRatio,
          child: VideoPlayer(controller!),
        ),
      );
    } else {
      return Container();
    }
  }
} 

Download Details:

Author: flutter

Source Code: https://github.com/flutter/packages/tree/main/packages/image_picker/image_picker

#flutter #picker 

Image Picker plugin for Flutter

Flutter Plugin for Picking Emojis using Device's Keyboard

The keyboard_emoji_picker package provides a simple way to use the device's native emoji keyboard to pick an emoji. It's currently supported on iOS only. However, adding support for Android is something I'd like to do in the future (if you'd like to help, please let me know).

Demo

Usage

To use KeyboardEmojiPicker, you need to have a KeyboardEmojiPickerWrapper widget somewhere in your widget tree. This widget will create a hidden input field in order to make opening the keyboard possible.

import 'package:keyboard_emoji_picker/keyboard_emoji_picker.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
	// While this example wraps [MaterialApp], you don't have to.
	// You can put it wherever you want to use the picker.
    return KeyboardEmojiPickerWrapper(
      child: MaterialApp(
        title: 'My App',
        home: MyHomePage(),
      ),
    );
  }
}

Checking if the keyboard is available

Since the package uses the device's keyboard, it's not always available. For example, if the user has disabled the emoji keyboard, it won't open and will throw a NoEmojiKeyboardFound exception.

To check if the keyboard is available, you can use the checkHasEmojiKeyboard method.

final hasEmojiKeyboard = await KeyboardEmojiPicker().checkHasEmojiKeyboard();

if (hasEmojiKeyboard) {
  // Open the keyboard.
} else {
  // Use another way to pick an emoji or show a dialog asking the user to
  // enable the emoji keyboard.
}

Picking an emoji

To pick an emoji, use the pickEmoji method. It will open the keyboard and wait for the user to pick an emoji. If the user closes the keyboard, the method will return null.

It is highly recommended to check if the keyboard is available before calling this method to avoid exceptions.

final emoji = await KeyboardEmojiPicker().pickEmoji();
if (emoji != null) {
  // Do something with the emoji
} else {
  // The emoji picking process was cancelled (usually, the keyboard was closed).
}

Closing the keyboard

Since the plugin uses a different hidden input than Flutter itself, you need to close the keyboard manually. To do so, use the closeKeyboard method.

KeyboardEmojiPicker().closeKeyboard();

Contributing

Contributions are welcome and appreciated! Feel free to open an issue or a pull request!

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add keyboard_emoji_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  keyboard_emoji_picker: ^1.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:keyboard_emoji_picker/keyboard_emoji_picker.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:keyboard_emoji_picker/keyboard_emoji_picker.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? _selectedEmoji;
  bool _hasKeyboard = false;
  final _pickEmojiResults = <String?>[];

  @override
  void initState() {
    super.initState();
    _checkHasEmojiKeyboard();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Emoji Picker Example'),
        ),
        body: Center(
          child: Column(children: [
            // You can have it anywhere you want.
            const KeyboardEmojiPickerWrapper(child: SizedBox.shrink()),
            const SizedBox(height: 16),
            ConstrainedBox(
              constraints: const BoxConstraints(minHeight: 84),
              child: Center(
                child: Text(
                  _selectedEmoji ??
                      'No emoji selected yet.\nPress the button below to pick one!',
                  style: TextStyle(
                    fontSize: _selectedEmoji == null ? 16 : 64,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
            TextButton(
              onPressed: () async {
                final emoji = await KeyboardEmojiPicker().pickEmoji();

                setState(() {
                  _pickEmojiResults.insert(0, emoji);
                  if (emoji != null) {
                    _selectedEmoji = emoji;
                  }
                });
              },
              child: const Text('Pick an emoji from the keyboard!'),
            ),
            TextButton(
              onPressed: KeyboardEmojiPicker().closeEmojiKeyboard,
              child: const Text('Close'),
            ),
            const SizedBox(height: 16),
            Text('Has emoji keyboard: $_hasKeyboard'),
            const Text('pickEmoji results:'),
            Expanded(
              child: ListView.builder(
                itemCount: _pickEmojiResults.length,
                itemBuilder: (context, index) {
                  final result = _pickEmojiResults[index];

                  return Text(
                    result.toString(),
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 40),
                  );
                },
              ),
            ),
          ]),
        ),
      ),
    );
  }

  void _checkHasEmojiKeyboard() async {
    final hasKeyboard = await KeyboardEmojiPicker().checkHasEmojiKeyboard();
    setState(() {
      _hasKeyboard = hasKeyboard;
    });
  }
} 

Download Details:

Author: person

Source Code: https://github.com/f-person/keyboard_emoji_picker

#flutter #picker #emoji 

Flutter Plugin for Picking Emojis using Device's Keyboard

Flutter Date Picker for Flutter Web application

Flutter Date Picker for Flutter Web application

Usage

    final textFieldKey = GlobalKey();
    ...
    TextField(
        key: textFieldKey,
        controller: _controller,
        onTap: () async {
            final pickedDate = await showWebDatePicker(
                context: textFieldKey.currentContext!,
                initialDate: _selectedDate,
            );
            if (pickedDate != null) {
                _selectedDate = pickedDate;
                _controller.text = pickedDate.toString();
            }
        },
    ),
    ...

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add vph_web_date_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  vph_web_date_picker: ^0.0.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:vph_web_date_picker/vph_web_date_picker.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:vph_web_date_picker/vph_web_date_picker.dart';

import 'material_theme/color_schemes.g.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late TextEditingController _controller;
  late DateTime _selectedDate;

  @override
  void initState() {
    super.initState();
    _selectedDate = DateTime.now();
    _controller = TextEditingController(text: _selectedDate.toString());
  }

  @override
  Widget build(BuildContext context) {
    final textFieldKey = GlobalKey();
    return MaterialApp(
      title: 'Web Date Picker Demo',
      theme: ThemeData(/* useMaterial3: true, */ colorScheme: lightColorScheme),
      darkTheme:
          ThemeData(/* useMaterial3: true, */ colorScheme: darkColorScheme),
      home: Scaffold(
        body: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 360.0),
          child: Padding(
            padding:
                const EdgeInsets.symmetric(horizontal: 16.0, vertical: 32.0),
            child: TextField(
              key: textFieldKey,
              controller: _controller,
              onTap: () async {
                final pickedDate = await showWebDatePicker(
                  context: textFieldKey.currentContext!,
                  initialDate: _selectedDate,
                );
                if (pickedDate != null) {
                  _selectedDate = pickedDate;
                  _controller.text = pickedDate.toString();
                }
              },
            ),
          ),
        ),
      ),
    );
  }
} 

Download Details:

Author: ngocvuphan

Source Code: https://github.com/ngocvuphan/flutter_web_date_picker

#flutter #picker 

Flutter Date Picker for Flutter Web application
Rupert  Beatty

Rupert Beatty

1675112040

The MacOS Color Picker As an App with More Features

System Color Picker

The familiar color picker supercharged

The macOS color picker as an app with lots of extra features.

Features

  • Quickly copy, paste, and convert colors in Hex, HSL, RGB, LCH format
  • Show as a normal app or in the menu bar
  • Pick a color or toggle the window from anywhere with a global keyboard shortcut
  • Make the window stay on top of all other windows
  • Launch it at login (when in the menu bar)
  • Recently picked colors
  • Shortcuts support
  • Hide menu bar icon

Tips

  • Press the Space key while using the color sampler to show the RGB values. The color sampler is a system component and it can unfortunately not show other kinds of color values.
  • Press the Option key when copying the Hex color to invert whether to include #.

Keyboard shortcuts

You can use the following keyboard shortcuts in the app:

  • Pick color: Command p
  • Copy as Hex: Shift Command h
  • Copy as HSL: Shift Command s
  • Copy as RGB: Shift Command r
  • Copy as LCH: Shift Command l
  • Paste color: Shift Command v (In the format Hex, HSL, RGB, or LCH)

Plugins

The built-in color picker supports plugins:

Screenshots

FAQ

The app does not show up in the menu bar

macOS hides menu bar apps when there is no space left in the menu bar. This is a common problem on MacBooks with a notch. Try quitting some menu bar apps to free up space. If this does not solve it, try quitting Bartender if you have it installed.

What is LCH color?

It's a more human-friendly color format.

Note that the LCH color is currently clamped to sRGB range.

The color changes if I copy and then paste it

That is because the default color space in the picker is Display P3, which is part of CSS Color 4, but the color space used for the legacy CSS color formats is sRGB (browsers are starting to handle color spaces but they are not all there yet).

How do I change the color space?

Right-click the color wheel. You probably want to select “sRGB”.

Note that the color strings will always be converted to sRGB color space.

Can you support SwiftUI.Color / UIColor / NSColor formats?

The best practice is to use Asset Catalog for colors instead of hard-coding the values in code. If you really want to hard-code colors, the Scala color picker plugin supports UIColor and NSColor.

Can I contribute localizations?

I don't have any immediate plans to localize the app.

Built with

  • Defaults - Swifty and modern UserDefaults
  • Regex - Swifty regular expressions
  • KeyboardShortcuts - Add user-customizable global keyboard shortcuts to your macOS app
  • LaunchAtLogin - Add “Launch at Login” functionality to your macOS app

Other apps

Download

Requires macOS 12 or later.

Older versions

Download Details:

Author: Sindresorhus
Source Code: https://github.com/sindresorhus/System-Color-Picker 
License: MIT license

#swift #macos #app #color #picker 

The MacOS Color Picker As an App with More Features
Rupert  Beatty

Rupert Beatty

1673952060

Colorful: iOS color picker built with Swift

Colorful

How to use it

Podfile

platform :ios, '10.0'
pod "Colorful", "~> 3.0"

Install

$ pod install

Usage

let colorPicker = ColorPicker(frame: ...)
colorPicker.addTarget(self, action: #selector(...), for: .valueChanged)
colorPicker.set(color: .red, colorSpace: .extendedSRGB)
view.addSubview(colorPicker)

You can receive .valueChanged event when user changes color.

Reason why you choose colorful

Beautiful UI with haptic feedback.

Wide color space support

ColorSpaceDescription
.extendedSRGBThe extended sRGB is color space for support wider and deeper representation of color.
.sRGBsRGB (standard Red Green Blue) is often the "default" color space for images that contain no color space information

Dark mode support

Requirements

iOS11 ~

Download Details:

Author: Hayashi311
Source Code: https://github.com/hayashi311/Color-Picker-for-iOS 
License: View license

#swift #ios #ui #color #picker #uikit 

Colorful: iOS color picker built with Swift
Ruthie  Blanda

Ruthie Blanda

1669690577

How to Use Material Datepicker in Angular 14

In this angular tutorial we will learn about How to Use Material Datepicker in angular 14. let’s discuss about angular 14 material datepicker format. you will learn material datepicker angular 14. We will use how to use material datepicker in angular 14.

Datepicker is a primary requirement of the project. we are almost required to use date picker in the angular app. angular provides material design and they provide how to use date picker in the angular application. I will show you here step by step how you can use material datepicker in angular.

In this example, we will add a material design theme and then import some dependency modules of datepicker. then we will simply write the code of datepicker from the angular document.

So, let's see bellow example from here:

Step 1: Create New App

You can easily create your angular app using below command:

ng new myDatepicker

Step 2: Add Material Design

Now in this step, we need to just install material design theme in our angular application. so let's add as like bellow:

ng add @angular/material

Cmd like bellow:

Installing packages for tooling via npm.

Installed packages for tooling via npm.

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink     

   [ Preview: https://material.angular.io?theme=indigo-pink ]

? Set up HammerJS for gesture recognition? Yes

? Set up browser animations for Angular Material? Yes

Step 3: Import Module

In third step, we need to import some dependency like MatDatepickerModule, MatNativeDateModule, MatInputModule. so let's add.

src/app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
     
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
  
@NgModule({
   declarations: [
      AppComponent
   ],
   imports:      [
    BrowserModule, 
    BrowserAnimationsModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatFormFieldModule,
    MatInputModule 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Use Datepicker

Now in view file, we will write code of input element with datepicker as like bellow:

src/app/app.component.html

<h1>Angular 14 Material Datepicker Example - ItSolutionStuff.Com</h1>
   
<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker ></mat-datepicker>
</mat-form-field>

Run Angular App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Angular app:

ng serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:4200

#angular 

How to Use Material Datepicker in Angular 14

A Color Picker Combining Fluttercandies and Cyclop By Rxlabz

blossom_color_picker

A color picker combining flutter_hsvcolor_picker by fluttercandies and cyclop by rxlabz. Made for Flutter Blossom.

Getting Started

import 'package:blossom_color_picker/blossom_color_picker.dart';

// for colorPicker
ColorPicker(
  color: Colors.blue,
  onColor: onColor,
),

// for opacity slider
OpacitySlider(
  opacity: opacity,
  selectedColor: color,
  onChange: onChange,
),

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add blossom_color_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  blossom_color_picker: ^1.2.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:blossom_color_picker/blossom_color_picker.dart'; 

example/lib/main.dart

import 'package:blossom_color_picker/blossom_color_picker.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double opacity = 1.0;
  Color color = Colors.blue;
  void onChanged(Color color) {
    setState(() {
      this.color = color;
    });
  }

  @override
  Widget build(BuildContext context) {
    return EyeDrop(
        child: Material(
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: CircleAvatar(
              backgroundColor: color.withOpacity(opacity),
            ),
          ),
          Divider(),
          ColorPicker(
            color: Colors.blue,
            onColor: onChanged,
          ),
          OpacitySlider(
            opacity: opacity,
            selectedColor: color,
            onChange: (o) {
              setState(() {
                opacity = o;
              });
            },
          )
        ],
      ),
    ));
  }
} 

Download Details:

Author: flutter-blossom

Source Code: https://github.com/flutter-blossom/blossom_color_picker

#flutter #picker 

A Color Picker Combining Fluttercandies and Cyclop By Rxlabz

Scheduled Date Picker with Flutter

Scheduled Date Picker

The scheduled date picker is a set of widgets that allows scheduling date. This can be useful in many scenarios, for scheduled tasks for example;

Demo

animated image

Getting Started

Installation

Add to pubspec.yaml in dependencies

  scheduled_date_picker: ^1.0.0

Usage

More usage details can be found on example folder

new ScheduledDatePicker(
    defaultLocale: 'pt',
    onStartDateChanged: (startDate) => print(startDate.toString()),
    onEndDateChanged: (endDate) => print(endDate.toString()),
    onScheduleDateChanged: (scheduleDate) =>
        print(scheduleDate.toString()),
    onTypeChanged: (type) => print(type.toString()),
    onWeekDaysChanged: (weekDays) =>
        print(weekDays.join(', ').toString()),
);

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add scheduled_date_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  scheduled_date_picker: ^2.0.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:scheduled_date_picker/scheduled_date_picker.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:scheduled_date_picker/scheduled_date_picker.dart';

void main() {
  runApp(SampleApp());
}

class SampleApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SampleAppState();
  }
}

class SampleAppState extends State<SampleApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Sample App')),
        body: ScheduledDatePicker(
          defaultLocale: 'pt',
          initialType: ScheduledDateType.CUSTOMIZED,
          initialWeekDays: [WeekDay.SEG, WeekDay.QUA, WeekDay.SEX],
          initialStartDate: DateTime.now().add(Duration(days: 5)),
          initialEndDate: DateTime.now().add(Duration(days: 15)),
          onStartDateChanged: (startDate) => print(startDate.toString()),
          onEndDateChanged: (endDate) => print(endDate.toString()),
          onScheduleDateChanged: (scheduleDate) =>
              print(scheduleDate.toString()),
          onTypeChanged: (type) => print(type.toString()),
          onWeekDaysChanged: (weekDays) =>
              print(weekDays.join(', ').toString()),
        ),
      ),
    );
  }
} 

Download Details:

Author: ViniciusSossela

Source Code: https://github.com/ViniciusSossela/scheduled-date-picker

#date #picker #flutter 

Scheduled Date Picker with Flutter

Building an Image Picker in Flutter

sparrow_image_picker_for_web

A web implementation of sparrow_image_picker.

Limitations on the web platform

Since Web Browsers don't offer direct access to their users' file system, this plugin provides a PickedFile abstraction to make access uniform across platforms.

The web version of the plugin puts network-accessible URIs as the path in the returned PickedFile.

URL.createObjectURL()

The PickedFile object in web is backed by URL.createObjectUrl Web API, which is reasonably well supported across all browsers:

Data on support for the bloburls feature across the major browsers from caniuse.com

However, the returned path attribute of the PickedFile points to a network resource, and not a local path in your users' drive. See Use the plugin below for some examples on how to use this return value in a cross-platform way.

input file "accept"

In order to filter only video/image content, some browsers offer an accept attribute in their input type="file" form elements:

Data on support for the input-file-accept feature across the major browsers from caniuse.com

This feature is just a convenience for users, not validation.

Users can override this setting on their browsers. You must validate in your app (or server) that the user has picked the file type that you can handle.

input file "capture"

In order to "take a photo", some mobile browsers offer a capture attribute:

Data on support for the html-media-capture feature across the major browsers from caniuse.com

Each browser may implement capture any way they please, so it may (or may not) make a difference in your users' experience.

pickImage()

The arguments maxWidth, maxHeight and imageQuality are not supported for gif images. The argument imageQuality only works for jpeg and webp images.

pickVideo()

The argument maxDuration is not supported on the web.

Usage

Import the package

This package is endorsed, which means you can simply use image_picker normally. This package will be automatically included in your app when you do.

Use the plugin

You should be able to use package:image_picker almost as normal.

Once the user has picked a file, the returned PickedFile instance will contain a network-accessible URL (pointing to a location within the browser).

The instance will also let you retrieve the bytes of the selected file across all platforms.

If you want to use the path directly, your code would need look like this:

...
if (kIsWeb) {
  Image.network(pickedFile.path);
} else {
  Image.file(File(pickedFile.path));
}
...

Or, using bytes:

...
Image.memory(await pickedFile.readAsBytes())
...

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add sparrow_image_picker_for_web

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  sparrow_image_picker_for_web: ^0.0.3

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:sparrow_image_picker_for_web/sparrow_image_picker_for_web.dart'; 

example/lib/main.dart

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

/// App for testing
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: Text('Testing... Look at the console output for results!'),
    );
  }
}

Download Details:

Author: hanguangbaihuo

Source Code: https://github.com/hanguangbaihuo/sparrow_image_picker/tree/master/sparrow_image_picker_for_web

#flutter #android #picker 

Building an Image Picker in Flutter
Rupert  Beatty

Rupert Beatty

1667570340

Image Picker Controller for IOS Written in Swift 4 & 5

DKImagePickerController

Image Picker Controller for IOS Written in Swift 4 & 5

Description

DKImagePickerController is a highly customizable, Pure-Swift library.

Features

  • Supports both single and multiple selection.
  • Supports filtering albums and sorting by type.
  • Supports landscape, iPad, and orientation switching.
  • iCloud Support.
  • Supports batch exports PHAsset to lcoal files.
  • Inline mode Support.
  • Customizable UICollectionViewLayout.
  • Customizable camera, photo gallery and photo editor.
  • Dark Mode Support

Requirements

  • iOS 9.0+ (Drop support for iOS 8 in 4.3.0 or above)
  • ARC
  • Swift 4 & 5

Installation

CocoaPods

iOS 9 and newer

DKImagePickerController is available on CocoaPods. Simply add the following line to your podfile:

# For latest release in cocoapods
pod 'DKImagePickerController'

For Swift 4.1

pod 'DKImagePickerController', :git => 'https://github.com/zhangao0086/DKImagePickerController.git', :branch => 'Swift4'

For iOS 8

pod 'DKImagePickerController', :git => 'https://github.com/zhangao0086/DKImagePickerController.git', :branch => 'iOS8'

Subspecs

There are 7 subspecs available now:

SubspecDescription
CoreRequired.
ImageDataManagerRequired. The subspec provides data to DKImagePickerController.
ResourceRequired. The subspec provides resource management and internationalization.
PhotoGalleryOptional. The subspec provides preview feature for PHAsset.
CameraOptional. The subspec provides camera feature.
InlineCameraOptional. The subspec should be pushed by UINavigationController, like UIImagePickerController with UIImagePickerControllerSourceType.camera.
PhotoEditorOptional. The subspec provides basic image editing features.

This means you can install only some of the DKImagePickerController modules. By default, you get all subspecs.
If you need to use your own photo editor, simply specify subspecs other than PhotoEditor:

pod 'DKImagePickerController', :subspecs => ['PhotoGallery', 'Camera', 'InlineCamera']

More information, see Extensions.

Carthage

github "zhangao0086/DKImagePickerController"

If you use Carthage to build your dependencies, make sure you have added CropViewController.framework, DKCamera.framework, DKImagePickerController.framework, DKPhotoGallery.framework and SDWebImage.framework to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase.

Getting Started

Initialization and presentation


let pickerController = DKImagePickerController()

pickerController.didSelectAssets = { (assets: [DKAsset]) in
    print("didSelectAssets")
    print(assets)
}

self.presentViewController(pickerController, animated: true) {}

​````

#### Configurations

​```swift
 /// Use UIDelegate to Customize the picker UI.
 @objc public var UIDelegate: DKImagePickerControllerBaseUIDelegate!
 
 /// Forces deselect of previous selected image. allowSwipeToSelect will be ignored.
 @objc public var singleSelect = false
 
 /// Auto close picker on single select
 @objc public var autoCloseOnSingleSelect = true
 
 /// The maximum count of assets which the user will be able to select, a value of 0 means no limit.
 @objc public var maxSelectableCount = 0
 
 /// Photos will be tagged with the location where they are taken.
 /// If true, your Info.plist should include the "Privacy - Location XXX" tag.
 open var containsGPSInMetadata = false
 
 /// Set the defaultAssetGroup to specify which album is the default asset group.
 public var defaultAssetGroup: PHAssetCollectionSubtype?
 
 /// Allow swipe to select images.
 @objc public var allowSwipeToSelect: Bool = false
 
 /// Allow select all
 @objc public var allowSelectAll: Bool = false
 
 /// A Bool value indicating whether the inline mode is enabled.
 @objc public var inline: Bool = false
 
 /// The type of picker interface to be displayed by the controller.
 @objc public var assetType: DKImagePickerControllerAssetType = .allAssets
 
 /// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored.
 @objc public var sourceType: DKImagePickerControllerSourceType = .both
 
 /// A Bool value indicating whether allows to select photos and videos at the same time.
 @objc public var allowMultipleTypes = true
 
 /// A Bool value indicating whether to allow the picker auto-rotate the screen.
 @objc public var allowsLandscape = false
 
 /// Set the showsEmptyAlbums to specify whether or not the empty albums is shown in the picker.
 @objc public var showsEmptyAlbums = true
 
 /// A Bool value indicating whether to allow the picker shows the cancel button.
 @objc public var showsCancelButton = false
 
 /// The block is executed when the user presses the cancel button.
 @objc public var didCancel: (() -> Void)?
 
 /// The block is executed when the user presses the select button.
 @objc public var didSelectAssets: ((_ assets: [DKAsset]) -> Void)?
 
 /// The block is executed when the number of selected assets is changed.
 @objc public var selectedChanged: (() -> Void)?
 
 /// A Bool value indicating whether to allow the picker to auto-export the selected assets to the specified directory when done is called.
 /// picker will creating a default exporter if exportsWhenCompleted is true and the exporter is nil.
 @objc public var exportsWhenCompleted = false
 
 @objc public var exporter: DKImageAssetExporter?
 
 /// Indicates the status of the exporter.
 @objc public private(set) var exportStatus = DKImagePickerControllerExportStatus.none {
    willSet {
        if self.exportStatus != newValue {
            self.willChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus))
        }
    }
    
    didSet {
        if self.exportStatus != oldValue {
            self.didChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus))
            
            self.exportStatusChanged?(self.exportStatus)
        }
    }
 }
 
 /// The block is executed when the exportStatus is changed.
 @objc public var exportStatusChanged: ((DKImagePickerControllerExportStatus) -> Void)?
 
 /// The object that acts as the data source of the picker.
 @objc public private(set) lazy var groupDataManager: DKImageGroupDataManager

Inline Mode

let groupDataManagerConfiguration = DKImageGroupDataManagerConfiguration()
groupDataManagerConfiguration.fetchLimit = 10
groupDataManagerConfiguration.assetGroupTypes = [.smartAlbumUserLibrary]

let groupDataManager = DKImageGroupDataManager(configuration: groupDataManagerConfiguration)

self.pickerController = DKImagePickerController(groupDataManager: groupDataManager)
pickerController.inline = true
pickerController.UIDelegate = CustomInlineLayoutUIDelegate(imagePickerController: pickerController)
pickerController.assetType = .allPhotos
pickerController.sourceType = .photo

let pickerView = self.pickerController.view!
pickerView.frame = CGRect(x: 0, y: 170, width: self.view.bounds.width, height: 200)
self.view.addSubview(pickerView)

Customizable UI

For example, see CustomUIDelegate.

Customizable Layout

For example, see CustomLayoutUIDelegate.

Conforms UIAppearance protocol

You can easily customize the appearance of the navigation bar using the appearance proxy.

UINavigationBar.appearance().titleTextAttributes = [
    NSFontAttributeName : UIFont(name: "Optima-BoldItalic", size: 21)!,
    NSForegroundColorAttributeName : UIColor.redColor()
]

Exporting to file

By default, the picker uses a singleton object of DKImageAssetExporter to export DKAsset to local files.

/*
 Configuration options for a DKImageAssetExporter.  When an exporter is created,
 a copy of the configuration object is made - you cannot modify the configuration
 of an exporter after it has been created.
 */
@objc
public class DKImageAssetExporterConfiguration: NSObject, NSCopying {
    
    @objc public var imageExportPreset = DKImageExportPresent.compatible
    
    /// videoExportPreset can be used to specify the transcoding quality for videos (via a AVAssetExportPreset* string).
    @objc public var videoExportPreset = AVAssetExportPresetHighestQuality
    
    #if swift(>=4.0)
    @objc public var avOutputFileType = AVFileType.mov
    #else
    @objc public var avOutputFileType = AVFileTypeQuickTimeMovie
    #endif
    
    @objc public var exportDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("DKImageAssetExporter")
}

/*
 A DKImageAssetExporter object exports DKAsset(PHAsset) from album (or iCloud) to the app's tmp directory (by default).
 It automatically deletes the exported directories when it receives a UIApplicationWillTerminate notification.
 */
@objc
open class DKImageAssetExporter: DKBaseManager {
    
    /// This method starts an asynchronous export operation of a batch of asset.
    @discardableResult
    @objc public func exportAssetsAsynchronously(assets: [DKAsset], completion: ((_ info: [AnyHashable : Any]) -> Void)?) -> DKImageAssetExportRequestID
}

This exporter can automatically convert HEIF to JPEG:

@objc
public enum DKImageExportPresent: Int {
    case
    compatible, // A preset for converting HEIF formatted images to JPEG.
    current     // A preset for passing image data as-is to the client.
}

You also can observe the export progress of each asset:

@objc
public protocol DKImageAssetExporterObserver {
    
    @objc optional func exporterWillBeginExporting(exporter: DKImageAssetExporter, asset: DKAsset)
    
    /// The progress can be obtained from the DKAsset.
    @objc optional func exporterDidUpdateProgress(exporter: DKImageAssetExporter, asset: DKAsset)
    
    /// When the asset's error is not nil, it indicates that an error occurred while exporting.
    @objc optional func exporterDidEndExporting(exporter: DKImageAssetExporter, asset: DKAsset)
}

extension DKAsset {
    
    /// The exported file will be placed in this location.
    /// All exported files can be automatically cleaned by the DKImageAssetDiskPurger when appropriate.
    @objc public var localTemporaryPath: URL?
    
    @objc public var fileName: String?
    
    /// Indicates the file's size in bytes.
    @objc public var fileSize: UInt
        
    /// If you export an asset whose data is not on the local device, and you have enabled downloading with the isNetworkAccessAllowed property, the progress indicates the progress of the download. A value of 0.0 indicates that the download has just started, and a value of 1.0 indicates the download is complete.
    @objc public var progress: Double
    
    /// Describes the error that occurred if the export has failed or been cancelled.
    @objc public var error: Error?
}

For example, see Export automatically and Export manually.

Extensions

This picker uses DKImageExtensionController manages all extensions, you can register it with a DKImageBaseExtension and a specified DKImageExtensionType to customize camera, photo gallery and photo editor:

/// Registers an extension for the specified type.
public class func registerExtension(extensionClass: DKImageBaseExtension.Type, for type: DKImageExtensionType)

public class func unregisterExtension(for type: DKImageExtensionType)

The perform function will be called with a dictionary providing current context information when an extension is triggered:

/// Starts the extension.
func perform(with extraInfo: [AnyHashable: Any])

/// Completes the extension.
func finish()

The extraInfo will provide different information for different DKImageExtensionType:

Camera

let didFinishCapturingImage = extraInfo["didFinishCapturingImage"] as? ((UIImage, [AnyHashable : Any]?) -> Void)
let didCancel = extraInfo["didCancel"] as? (() -> Void)

For a custom camera example, see CustomCameraExtension.

InlineCamera

The extraInfo is the same as for Camera.

Photo Gallery

let groupId = extraInfo["groupId"] as? String
let presentationIndex = extraInfo["presentationIndex"] as? Int
let presentingFromImageView = extraInfo["presentingFromImageView"] as? UIImageView

Photo Editor

let image = extraInfo["image"] as? UIImage
let didFinishEditing = extraInfo["didFinishEditing"] as? ((UIImage, [AnyHashable : Any]?) -> Void)
let metadata = extraInfo["metadata"] as? [AnyHashable : Any]

How to use in Objective-C

If you use CocoaPods

Add the following two lines into your Podfile:

pod 'DKImagePickerController'
use_frameworks!

Import the library into your Objective-C file:

#import <DKImagePickerController/DKImagePickerController-Swift.h>

If you use it directly in your project

See also:Swift and Objective-C in the Same Project

Drag and drop the DKCamera, DKImageManager and DKImagePickerController to your project

Import the library into your Objective-C file:

#import "YourProductModuleName-Swift.h"

then you can:

DKImagePickerController *pickerController = [DKImagePickerController new];

 [pickerController setDidSelectAssets:^(NSArray * __nonnull assets) {
     NSLog(@"didSelectAssets");
 }];
 
 [self presentViewController:pickerController animated:YES completion:nil];

Localization

The default supported languages:

en, es, da, de, fr, hu, ja, ko, nb-NO, pt_BR, ru, tr, ur, vi, ar, it, zh-Hans, zh-Hant

You can also add a hook to return your own localized string:

DKImagePickerControllerResource.customLocalizationBlock = { title in
    if title == "picker.select.title" {
        return "Test(%@)"
    } else {
        return nil
    }
}

or images:

DKImagePickerControllerResource.customImageBlock = { imageName in
    if imageName == "camera" {
        return DKImagePickerControllerResource.photoGalleryCheckedImage()
    } else {
        return nil
    }
}

Contributing to this project

If you have feature requests or bug reports, feel free to help out by sending pull requests or by creating new issues.

Download Details:

Author: zhangao0086
Source Code: https://github.com/zhangao0086/DKImagePickerController 
License: MIT license

#swift #picker #image 

Image Picker Controller for IOS Written in Swift 4 & 5

A Flutter Widget Library Which Helps Us to Select Days in A Week

Day Picker

A Flutter widget library which helps us to select days in a week.

Screenshot

Screenshot week day picker Screenshot week day picker

Usage

Add day_picker to your pubspec.yaml file.

    flutter:
      sdk: flutter
    day_picker: 2.1.0

import the package:

import 'package:day_picker/day_picker.dart';

Constructor for the day_picker is given below.

    SelectWeekDays({
    required this.onSelect,
    this.backgroundColor,
    this.fontWeight
    this.fontSize
    this.daysFillColor,
    this.daysBorderColor,
    this.selectedDayTextColor,
    this.unSelectedDayTextColor,
    this.border = true,
    this.boxDecoration,
    this.padding = 8.0,
    required this.days,
    Key? key,
  }) : super(key: key);

Example here creates a day_picker with below style [with Gradient and no borders].

Screenshot week day picker


    List<DayInWeek> _days = [
    DayInWeek(
      "Sun",
    ),
    DayInWeek(
      "Mon",
    ),
    DayInWeek(
      "Tue",
      isSelected: true
    ),
    DayInWeek(
      "Wed",
    ),
    DayInWeek(
      "Thu",
    ),
    DayInWeek(
      "Fri",
    ),
    DayInWeek(
      "Sat",
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Select days in week"),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: SelectWeekDays(
            fontSize:14,
            fontWeight: FontWeight.w500,
            days: _days
            border: false,
            boxDecoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30.0),
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                colors: [const Color(0xFFE55CE4), const Color(0xFFBB75FB)],
                tileMode:
                    TileMode.repeated, // repeats the gradient over the canvas
              ),
            ),
            onSelect: (values) { // <== Callback to handle the selected days
                print(values);
            },
          ),
        ),
      ),
    );

Pass a callback to the onSelect property with parameter of type List<String>.


Pass a list of days of type DayInWeek into days property

class DayInWeek {

  String dayName;
  bool isSelected = false;

  DayInWeek(this.dayName, {this.isSelected = false});
}

DayInWeek consist of two Properties [dayName] and [isSelected]. By default [isSelected] value will be false


Example:

void handleOnSelect(List<String> value){
    //TODO: Manipulate the List of days selected
    print(value);
}

Customization

PropertyTypeDescription
onSelectList<String>Callback invoked when days are selected
daysList<DayInWeek>List of days that need to be passed
paddingdoublePadding between container and the buttons [by default it is 8.0]
boxdecorationBoxDecorationprovides variety of ways to style the background container[gradient, color, border radius]
backgroundColorColorProperty to change the color of the container
fontSizedoubleProperty to change size of font
fontWeightFontWeightProperty to change the font weight of text
daysFillColorColorProperty to change the color of rounded buttons when the days are selected
daysBorderColorColorProperty to change the border color of rounded button
selectedDayTextColorColorproperty to change the text color of the selected days
unSelectedDayTextColorColorproperty to change the text color when the days are not selected
borderboolSet this property to false if border is not needed around the rounded buttons[by default this property will be true]

Contributions

Contributions of any kind are more than welcome😊! Feel free to fork and improve day_picker or open an issue.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add day_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  day_picker: ^2.1.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:day_picker/day_picker.dart'; 

example/lib/main.dart

import 'package:day_picker/day_picker.dart';
import 'package:day_picker/model/day_in_week.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  List<DayInWeek> _days = [
    DayInWeek(
      "Zo",
    ),
    DayInWeek(
      "Ma",
    ),
    DayInWeek(
      "Di",
    ),
    DayInWeek(
      "Wo",
    ),
    DayInWeek(
      "Do",
    ),
    DayInWeek("Vr", isSelected: true),
    DayInWeek("Za", isSelected: true),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Select days in week"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SelectWeekDays(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              days: _days,
              onSelect: (values) {
                print(values);
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SelectWeekDays(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              days: _days,
              border: false,
              boxDecoration: BoxDecoration(
                borderRadius: BorderRadius.circular(30.0),
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  // 10% of the width, so there are ten blinds.
                  colors: [const Color(0xFFE55CE4), const Color(0xFFBB75FB)], // whitish to gray
                  tileMode: TileMode.repeated, // repeats the gradient over the canvas
                ),
              ),
              onSelect: (values) {
                print(values);
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SelectWeekDays(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              days: _days,
              boxDecoration: BoxDecoration(
                borderRadius: BorderRadius.circular(30.0),
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  // 10% of the width, so there are ten blinds.
                  colors: [const Color(0xFFE55CE4), const Color(0xFFBB75FB)], // whitish to gray
                  tileMode: TileMode.repeated, // repeats the gradient over the canvas
                ),
              ),
              onSelect: (values) {
                print(values);
              },
            ),
          ),
          SelectWeekDays(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            days: _days,
            backgroundColor: Color(0xFF303030),
            onSelect: (values) {
              print(values);
            },
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SelectWeekDays(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              days: _days,
              border: false,
              backgroundColor: Color(0xFF303030),
              onSelect: (values) {
                print(values);
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SelectWeekDays(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              days: _days,
              border: false,
              boxDecoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(30.0),
              ),
              onSelect: (values) {
                print(values);
              },
            ),
          ),
        ],
      ),
    );
  }
} 

Download Details:

Author: shan-shaji

Source Code: https://github.com/shan-shaji/day_picker

#flutter #widget #picker 

A Flutter Widget Library Which Helps Us to Select Days in A Week

A Customable Time Picker using Analog Clock Format

A customable time picker using analog clock format

Features

  • Customizable background color and widget
  • Customizable clock hand color and widget
  • Ability to change period AM/PM type via Controller
  • Fluid animation movement of clock hand

Screenshot

Demo Video

Getting started

Add package to pubspec.yaml

dependencies:
    analog_clock_picker: 0.0.6

How to use

Create controller for control the value of the clock

AnalogClockController analogClockController = AnalogClockController();

You can provide default value inside the controller

AnalogClockController analogClockController = AnalogClockController(
  value: DateTime.now(),
  periodType: PeriodType.am,
  onPeriodTypeChange: (date, period) {
    //TODO : Do Something
  },
);

you can set period change listener after initialize it

analogClockController.setOnPeriodTypeChangeListener((date, period) {
      //TODO : Do Something
});

Minimal usage

AnalogClockPicker(
  controller: analogClockController,
  size: MediaQuery.of(context).size.width * 0.74,
  secondHandleColor: Colors.red,
  minutesHandleColor: Colors.black,
  hourHandleColor: Colors.black,
  clockBackground: Image.asset(
    AssetImages.clockBackground,
  ),
  onClockChange: (date){
    //TODO : Do Something
  },
)

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add analog_clock_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  analog_clock_picker: ^0.0.6

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:analog_clock_picker/analog_clock_picker.dart'; 

example/lib/main.dart

import 'package:analog_clock_picker/analog_clock_picker.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  AnalogClockController analogClockController = AnalogClockController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Analog clock picker",
        ),
      ),
      body: SizedBox(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnalogClockPicker(
              clockBackground: Image.asset(
                "assets/images/clock_background.png",
              ),
              clockBackgroundColor: Colors.white,
              secondHandleColor: Colors.red,
              minutesHandleColor: Colors.black,
              hourHandleColor: Colors.black,
              controller: analogClockController,
              size: MediaQuery.of(context).size.width * 0.68,
            ),
            ValueListenableBuilder<DateTime>(
              valueListenable: analogClockController,
              builder: (context, value, _) {
                return Container(
                  margin: const EdgeInsets.only(top: 42),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        margin: const EdgeInsets.only(right: 12),
                        child: Text(
                          DateFormat("HH:mm").format(value),
                          style: const TextStyle(
                            fontSize: 40,
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          analogClockController.setPeriodType(
                            analogClockController.periodType == PeriodType.am
                                ? PeriodType.pm
                                : PeriodType.am,
                          );
                        },
                        child: Text(
                          analogClockController.periodType == PeriodType.am
                              ? "AM"
                              : "PM",
                          style: const TextStyle(
                            fontSize: 18,
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
} 

Download Details:

Author: yasfdany

Source Code: https://github.com/yasfdany/analog_clock_picker

#picker #analog #clock 

A Customable Time Picker using Analog Clock Format

Picker Control in Flutter

dh_picker 选择器控件

num_picker 数字选择器

数字选择器

max 最大值

min 最小值

interval 间隔值

indexFormat 格式化函数,可以格式化每项

NumberPicker(
    max: 21,
    min: 1,
    interval: 2,
    indexFormat: (value) => "$value+",
    itemExtent: 40,
    onSelectedItemChanged: (value) {
      print('selected  value: $value');
    },
    labelAlignment: Alignment.center,
    label: Text("℃"),
    labelPadding: EdgeInsets.only(left: 50, bottom: 16),
  ),
)

string_picker 字符串选择器

字符串选择器

StringPicker(
    itemExtent: 40,
    data: ['Apple', 'Bob', 'Cat'],
    onSelectedItemChanged: (String value) {
      print('selected  value: $value');
    },
  )

date_picker 日期时间选择器,参考flutter_date_picker

字符串选择器

pickerOverlay 选择器上面覆盖层,通常用于自定义selectionOverlay

每个选择器都可以设置selectionOverlay,可能达不到逾期效果,通过设置pickerOverlay 解决,注意设置selectionOverlayBuilder: (int index) => null

showPicker(context, builder: (BuildContext context) {
  return DateTimePickerWidget(
    onConfirm: (DateTime dateTime) {
      selectTime = dateTime;
      print('date time: $dateTime');
    },
    title: "选择日期",
    titleActionTheme: TitleActionTheme(
      decoration: ShapeDecoration(
          color: Colors.white,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10.0),
                  topRight: Radius.circular(10.0)))),
    ),
    onCancel: () {
      print('取消了');
    },
    pickerTheme: PickerTheme(
      height: 180.0,
    ),
    pickerModel: DateTimePickerModel(
      maxTime: DateTime(2022, 12, 1, 5, 6),
      minTime: DateTime(2020, 11, 2, 3, 4),
      currentTime: selectTime,
    ),
    pickerOverlay: Row(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        SizedBox(
          width: 18,
        ),
        Expanded(
            child: DefaultSelectionOverlay(
          borderColor: Colors.red,
        )),
        SizedBox(
          width: 27,
        ),
        Expanded(
            child: DefaultSelectionOverlay(
          borderColor: Colors.red,
        )),
        SizedBox(
          width: 27,
        ),
        Expanded(
            child: DefaultSelectionOverlay(
          borderColor: Colors.red,
        )),
        SizedBox(
          width: 18,
        ),
      ],
    ),
    selectionOverlayBuilder: (int index) => null,
  );
});

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add dh_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  dh_picker: ^1.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:dh_picker/dh_picker.dart'; 

example/lib/main.dart

import 'package:dh_picker/dh_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  var local = 'zh';
  Intl.defaultLocale = local;

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    DateTime selectTime;

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          SizedBox(
            height: 20,
          ),
          Container(
            height: 150,
            child: NumberPicker(
              max: 21,
              min: 1,
              interval: 2,
              indexFormat: (value) => "$value+",
              itemExtent: 40,
              onSelectedItemChanged: (value) {
                print('selected  value: $value');
              },
              labelAlignment: Alignment.center,
              label: Text("℃"),
              labelPadding: EdgeInsets.only(left: 50, bottom: 16),
            ),
          ),
          DateTimePicker(
            pickerModel: DatePickerModel(
              maxTime: DateTime(2028, 12, 1, 5, 6),
              minTime: DateTime(2012, 11, 2, 3, 4),
              weights: [1, 1, 1],
              labels: [true, true, true],
              formats: ['yyyy', 'M', 'dd'],
            ),
            onDateTimeChanged: (DateTime value) {
              print('date time :  $value');
            },
            theme: PickerTheme(
              padding: EdgeInsets.symmetric(horizontal: 20),
            ),
          ),
          TextButton(
            onPressed: () {
              showPicker(context, builder: (BuildContext context) {
                return DateTimePickerWidget(
                  onConfirm: (DateTime dateTime) {
                    selectTime = dateTime;
                    print('date time: $dateTime');
                  },
                  title: "选择日期",
                  titleActionTheme: TitleActionTheme(
                    decoration: ShapeDecoration(
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(10.0),
                                topRight: Radius.circular(10.0)))),
                  ),
                  onCancel: () {
                    print('取消了');
                  },
                  pickerTheme: PickerTheme(
                    height: 180.0,
                    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  ),
                  pickerModel: DateTimePickerModel(
                    maxTime: DateTime(2022, 12, 1, 5, 6, 7),
                    minTime: DateTime(2020, 11, 2, 3, 4, 5),
                    currentTime: selectTime,
                    // weights: [2, 1, 1, 1, 1, 0],
                    dividers: ['', '/', '', ':', ''],
                  ),
                  pickerOverlay: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      SizedBox(
                        width: 18,
                      ),
                      Expanded(
                        flex: 2,
                          child: DefaultSelectionOverlay(
                        borderColor: Colors.red,
                      )),
                      SizedBox(
                        width: 18,
                      ),
                      Expanded(
                        flex: 3,
                          child: DefaultSelectionOverlay(
                        borderColor: Colors.red,
                      )),
                      SizedBox(
                        width: 18,
                      ),
                      Expanded(
                        flex: 3,
                          child: DefaultSelectionOverlay(
                        borderColor: Colors.red,
                      )),
                      SizedBox(
                        width: 18,
                      ),
                    ],
                  ),
                  selectionOverlayBuilder: (int index) => null,
                  // header: Container(
                  //   padding: EdgeInsets.only(top: 20, bottom: 10),
                  //   color: Colors.white,
                  //   child: Row(
                  //     children: [
                  //       Expanded(
                  //           child: Center(
                  //         child: Text("结束日期"),
                  //       )),
                  //       Expanded(
                  //           child: Center(
                  //         child: Text("结束时间"),
                  //       ))
                  //     ],
                  //   ),
                  // ),
                );
              });
            },
            child: Text("show date picker"),
          ),
        ],
      ),
    );
  }
} 

Download Details:

Author: evansherry

Source Code: https://github.com/evansherry/dh_picker

#flutter #picker 

Picker Control in Flutter

File Picker plugin for Flutter

File Picker

A package that allows you to use the native file explorer to pick single or multiple files, with extensions filtering support.

Currently supported features

  • Uses OS default native pickers
  • Supports multiple platforms (Mobile, Web, Desktop and Flutter GO)
  • Pick files using custom format filtering — you can provide a list of file extensions (pdf, svg, zip, etc.)
  • Pick files from cloud files (GDrive, Dropbox, iCloud)
  • Single or multiple file picks
  • Different default type filtering (media, image, video, audio or any)
  • Picking directories
  • Load file data immediately into memory (Uint8List) if needed;
  • Open a save-file / save-as dialog (a dialog that lets the user specify the drive, directory, and name of a file to save)

If you have any feature that you want to see in this package, please feel free to issue a suggestion. 🎉

Compatibility Chart

APIAndroidiOSLinuxmacOSWindowsWeb
clearTemporaryFiles()
getDirectoryPath()
pickFiles()
saveFile()

See the API section of the File Picker Wiki or the official API reference on pub.dev for further details.

Documentation

See the File Picker Wiki for every detail on about how to install, setup and use it.

File Picker Wiki

  1. Installation
  2. Setup
  3. API
  4. FAQ
  5. Troubleshooting

Usage

Quick simple usage example:

Single file

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  File file = File(result.files.single.path);
} else {
  // User canceled the picker
}

Multiple files

FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

if (result != null) {
  List<File> files = result.paths.map((path) => File(path)).toList();
} else {
  // User canceled the picker
}

Multiple files with extension filter

FilePickerResult? result = await FilePicker.platform.pickFiles(
  type: FileType.custom,
  allowedExtensions: ['jpg', 'pdf', 'doc'],
);

Pick a directory

String? selectedDirectory = await FilePicker.platform.getDirectoryPath();

if (selectedDirectory == null) {
  // User canceled the picker
}

Save-file / save-as dialog

String? outputFile = await FilePicker.platform.saveFile(
  dialogTitle: 'Please select an output file:',
  fileName: 'output-file.pdf',
);

if (outputFile == null) {
  // User canceled the picker
}

Load result and file details

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  PlatformFile file = result.files.first;

  print(file.name);
  print(file.bytes);
  print(file.size);
  print(file.extension);
  print(file.path);
} else {
  // User canceled the picker
}

Pick and upload a file to Firebase Storage with Flutter Web

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  Uint8List fileBytes = result.files.first.bytes;
  String fileName = result.files.first.name;
  
  // Upload file
  await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
}

For full usage details refer to the Wiki above.

Example App

Android

Demo

iOS

DemoMultiFilters

MacOS

DemoMacOS

Linux

DemoLinux

Windows

DemoWindows

Getting Started

For help getting started with Flutter, view our online documentation.

For help on editing plugin code, view the documentation

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add file_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  file_picker: ^5.2.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:file_picker/file_picker.dart'; 

example/lib/main.dart

import 'package:file_picker_example/src/file_picker_demo.dart';
import 'package:flutter/widgets.dart';

void main() => runApp(FilePickerDemo()); 

Download Details:

Author: miguelpruivo

Source Code: https://github.com/miguelpruivo/flutter_file_picker

#flutter #picker 

 File Picker plugin for Flutter