Skip to content

Instantly share code, notes, and snippets.

@RyanRamchandar
Created February 16, 2020 03:38
Show Gist options
  • Save RyanRamchandar/82f6f8091fca852618a6ef30bdbc9e86 to your computer and use it in GitHub Desktop.
Save RyanRamchandar/82f6f8091fca852618a6ef30bdbc9e86 to your computer and use it in GitHub Desktop.
Flutter widget to Google Maps Marker icon
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:example_flutter/utils/widget_utils.dart';
void main() {
testWidgets('create image from widget', (WidgetTester tester) async {
final globalKey = GlobalKey();
final widget = MaterialApp(
home: Container(
color: Colors.red,
child: RepaintBoundary(
key: globalKey,
child: Center(
child: Container(
width: 100,
height: 100,
color: Colors.grey,
child: Center(child: FlutterLogo(size: 100)),
),
),
),
),
);
await tester.pumpWidget(widget);
final Uint8List markerIcon = await widgetToUint8List(key: globalKey, pixelRatio: 1.0);
final Marker marker = Marker(icon: BitmapDescriptor.fromBytes(markerIcon));
});
}
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
// From:
// https://api.flutter.dev/flutter/rendering/RenderRepaintBoundary/toImage.html
Future<Uint8List> widgetToUint8List({GlobalKey key, double pixelRatio}) async {
RenderRepaintBoundary boundary = key.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return byteData.buffer.asUint8List();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment