Skip to content

Instantly share code, notes, and snippets.

@xantiagoma
Last active July 19, 2022 16:23
Show Gist options
  • Save xantiagoma/2cf468a8199bfeb7bb964470328998cf to your computer and use it in GitHub Desktop.
Save xantiagoma/2cf468a8199bfeb7bb964470328998cf to your computer and use it in GitHub Desktop.
Dart utils
Future<Map<K, V>> awaitForMap<K, V>(Map<K, Future<V>> map) async {
final m = Map<K, V>();
for (final K key in map.keys) {
try {
m[key] = await map[key];
} catch (e) {
print(e);
m[key] = null;
}
}
return m;
}
import 'dart:async';
import 'dart:math' as math;
Iterable<double> genDeltas(double min, double max, int cycles) sync* {
if (min == max) return;
final double delta = (max - min) / cycles;
double value = min;
do {
yield value;
value = value + delta;
} while (value <= max);
yield max;
}
Iterable<double> syncTween(double begin, double end, int cycles) {
final min = math.min(begin, end);
final max = math.max(begin, end);
final isReversed = begin > end;
final deltas = genDeltas(min, max, cycles);
if (isReversed) {
return deltas.toList().reversed;
}
return deltas;
}
Stream<double> tween(double begin, double end, int cycles,
{Duration delay = Duration.zero}) async* {
for (final value in syncTween(begin, end, cycles)) {
yield value;
await Future.delayed(delay);
}
}
import 'package:flutter/material.dart';
Color cssColorToColor(String hex, [int opacity = 255]) {
final prefix = opacity.toRadixString(16);
hex = hex.replaceFirst('#', '');
hex = hex.length == 6 ? prefix + hex : hex;
final int val = int.parse(hex, radix: 16);
final color = Color(val);
return color;
}
String colorToCssColor(Color color, {bool useHexInRGBA = false}) {
final String hex = color.value.toRadixString(16);
final String sufix = hex.substring(2, hex.length);
final String prefix = hex.substring(0, 2);
final bool notNeedAlphaChannel = prefix.toLowerCase() == "ff";
if (notNeedAlphaChannel) {
return "#$sufix";
}
return useHexInRGBA
? "#$sufix$prefix"
: "rgba(${color.red}, ${color.green}, ${color.blue}, ${color.opacity})";
}
double toRadians(double num) {
return num * pi / 180;
}
///
/// This uses the ‘haversine’ form,ula to calculate the great-circle distance
/// between two points – that is, the shortest distance over the earth’s
/// surface – giving an ‘as-the-crow-flies’ distance between the
/// points (ignoring any hills they fly over, of course!).
/// More at: https://www.movable-type.co.uk/scripts/latlong.html
/// @param {number} lat1
/// @param {number} lon1
/// @param {number} lat2
/// @param {number} lon2
/// @returns {number} Distance in meters
double getDistance(double lat1, double lon1, double lat2, double lon2) {
const EARTH_RADIUS = 6371e3; // metres (mean radius = 6,371km)
final latitude1 = toRadians(lat1);
final latitude2 = toRadians(lat2);
final diffLatitude = toRadians(lat2 - lat1);
final diffLongitude = toRadians(lon2 - lon1);
final a = sin(diffLatitude / 2) * sin(diffLatitude / 2) +
cos(latitude1) *
cos(latitude2) *
sin(diffLongitude / 2) *
sin(diffLongitude / 2);
final c = 2 * atan2(sqrt(a), sqrt(1 - a));
final d = EARTH_RADIUS * c;
return d;
}
double distanceBetween(LatLng loc1, LatLng loc2) {
return getDistance(
loc1.latitude, loc1.longitude, loc2.latitude, loc2.longitude);
}
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
Future<Uint8List> getBytesFromCanvas(int width, int height, urlAsset) async {
final ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
final Canvas canvas = Canvas(pictureRecorder);
final Paint paint = Paint()..color = Colors.transparent;
final Radius radius = Radius.circular(20.0);
canvas.drawRRect(
RRect.fromRectAndCorners(
Rect.fromLTWH(0.0, 0.0, width.toDouble(), height.toDouble()),
topLeft: radius,
topRight: radius,
bottomLeft: radius,
bottomRight: radius,
),
paint);
final ByteData datai = await rootBundle.load(urlAsset);
var imaged = await loadImage(new Uint8List.view(datai.buffer));
canvas.drawImage(imaged, new Offset(0, 0), new Paint());
final img = await pictureRecorder.endRecording().toImage(width, height);
final data = await img.toByteData(format: ui.ImageByteFormat.png);
return data.buffer.asUint8List();
}
Future<ui.Image> loadImage(List<int> img) async {
final Completer<ui.Image> completer = new Completer();
ui.decodeImageFromList(img, (ui.Image img) {
return completer.complete(img);
});
return completer.future;
}
Future<Uint8List> getBytesFromAsset(String path, int width) async {
ByteData data = await rootBundle.load(path);
ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
targetWidth: width);
ui.FrameInfo fi = await codec.getNextFrame();
return (await fi.image.toByteData(format: ui.ImageByteFormat.png))
.buffer
.asUint8List();
}
Future< Map<String, dynamic> > reverseLocation({
@required double lat,
@required double long,
int zoom: 18,
bool addressdetails: true,
bool extratags: true,
bool namedetails: true,
}) async {
Response resp = await get(
"https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=$lat&lon=$long&zoom=$zoom&addressdetails=${addressdetails ? 1 : 0}&extratags=${extratags ? 1 : 0}&namedetails=${namedetails ? 1 : 0}");
return resp.body;
}
Stream<LatLng> getLocation() async* {
Geolocator geolocator = Geolocator();
LocationPermissions locationPermissions = LocationPermissions();
// if(await have permission)
// Check what ever if can get with native plugin
// else fallback to get from ip
PermissionStatus permission =
await locationPermissions.checkPermissionStatus();
if (permission == PermissionStatus.unknown ||
permission == PermissionStatus.denied ||
permission == null) {
await LocationPermissions().requestPermissions();
}
GeolocationStatus perStatus =
await geolocator.checkGeolocationPermissionStatus();
if (perStatus == GeolocationStatus.denied ||
perStatus == GeolocationStatus.disabled ||
perStatus == null ||
perStatus == GeolocationStatus.unknown) {
var response = await http.get("https://ipapi.co/json/");
var ipapiRes = IpApiCo.fromJson(response.body);
yield LatLng(ipapiRes.latitude, ipapiRes.longitude);
} else {
LocationOptions locationOptions = LocationOptions(
accuracy: LocationAccuracy.high,
distanceFilter: 10,
timeInterval: 3000);
Stream<LatLng> flow = geolocator
.getPositionStream(locationOptions)
.map((pos) => LatLng(pos.latitude, pos.longitude));
yield* flow;
}
}
import 'package:flutter/material.dart';
// RestartWidget.restartApp(context)
class RestartWidget extends StatefulWidget {
final Widget child;
RestartWidget({this.child});
static restartApp(BuildContext context) {
final _RestartWidgetState state =
context.ancestorStateOfType(const TypeMatcher<_RestartWidgetState>());
state.restartApp();
}
@override
_RestartWidgetState createState() => new _RestartWidgetState();
}
class _RestartWidgetState extends State<RestartWidget> {
Key key = new UniqueKey();
void restartApp() {
this.setState(() {
key = new UniqueKey();
});
}
@override
Widget build(BuildContext context) {
return new Container(
key: key,
child: widget.child,
);
}
}
import 'package:flutter/material.dart';
void showText(BuildContext context, String text) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(text),
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment