Trying to import package d3/d3.js in Angular dart. - d3.js

I have moved from Java to AngularDart for a project where I have to visualise some numbers and a threat level based on data.
I decided to try to do a pie/doughnut shape with pie slices showing data properties and the centre is to show the threat level as a coloured circle.
I found an old D3Dart package and used that for my first attempt. Works fine. I can build arc's including inner- and outer radius, start- and end-angle, etc.
Reading examples on how to build I was inspired to try and move to d3/d3.js, which has (I guess) a better interface to d3.js. I need to be able to better control how I display things f.ex. replace a node element in the DOM.
When tying to import the package with import 'package:d3/d3.js' as d3;
pub serve fails with the message:
> D:\apps\Dart\dart-sdk\bin\pub.bat serve web --port=54969 Loading
> source assets... Loading angular, test/pub_serve and
> dart_to_js_script_rewriter transformers... Serving SimplePie web on
> http://localhost:54969 [web] GET Served 2 assets. [web] GET styles.css
> => SimplePie|web/styles.css Build error: Transform BuilderTransformer: Instance of 'TemplatePlaceholderBuilder' on SimplePie|primary threw
> error: Error in <unknown source>: Illegal character '949'.
>
> Error in <unknown source>: Illegal character '949'.
Last line is repeated many times.
What am I missing in my import
pubspec.yaml:
name: SimplePie
description: A web app that uses AngularDart Components
version: 0.0.1
environment:
sdk: '>=1.24.0 <2.0.0'
dependencies:
color: any
angular: ^4.0.0
angular_components: ^0.8.0
d3: ^0.2.0
dev_dependencies:
angular_test: ^1.0.0
browser: ^0.10.0
dart_to_js_script_rewriter: ^1.0.1
test: ^0.12.0
transformers:
- angular:
entry_points:
- web/main.dart
- test/**_test.dart
- test/pub_serve:
$include: test/**_test.dart
- dart_to_js_script_rewriter
Snippet of my dart code that fails when I add d3/d3.js:
import 'dart:html';
import 'dart:math' as Math;
import 'package:d3/d3.js' as d3;
import 'package:angular_components/angular_components.dart';
import 'package:angular/angular.dart';
#Component (
selector: "pie-chart",
templateUrl: 'pie_chart.html',
directives: const[CORE_DIRECTIVES, materialDirectives],
providers: const[materialProviders]
)
class SimplePie implements AfterViewInit {
#ViewChild("containerPieChart")
List<num> pieSliceList;
num numberOfSlices;
Math.Random random = new Math.Random();
final num MAX_PIE_SLICE_SIZE = 20;
num totalPieSize;
num width;
num height;
num radius;
num strokeWidth;
var progressText;
void ngAfterViewInit() {
setup();
totalPieSize = 0;
for (num i = 0 ; i < random.nextInt(10) ; i++ ) {
var value = random.nextInt(MAX_PIE_SLICE_SIZE);
pieSliceList.add(value);
totalPieSize += value;
}
numberOfSlices = pieSliceList.length;
progressText = document.getElementById("progressText");
}
void setup () {
this.width = 800;
this.height = 800;
this.strokeWidth = 3;
this.radius = (Math.min(width, height) / 2) - 2 * strokeWidth;
}
}
I use IntelliJ IDE (latest) and Dart version 1.24.3.

Related

I am searching for a Flutter package which can find the barcode of a .pdf file

I am trying to build an application on Windows, which i pick (.pdf) files that contain a barcode on them.
I want to find and extract the barcode info and put it on a list.
I need a package that it can make it happen. A package except https://pub.dev/packages/flutter_barcode_sdk because it has an annually cost for its licence.
I spent some time writing this for you and I made it using two different packages.
This one is able to read barcodes from camera and files
scan: 1.6.0
But I could not make it read PDFs, so I installed another package to render images from PDF files.
native_pdf_renderer: 3.1.0
This package is also required:
path_provider: ^2.0.11
This is the code that worked fine for me:
import 'dart:async';
import 'dart:io';
import 'package:native_pdf_renderer/native_pdf_renderer.dart';
import 'package:path_provider/path_provider.dart';
import 'package:scan/scan.dart';
Future<void> readBarcodeFromPDF(String assetPath) async {
PdfDocument pdf = await PdfDocument.openAsset(assetPath);
for (var pageIndex = 0; pageIndex < pdf.pagesCount; pageIndex++) {
final page = await pdf.getPage(pageIndex);
final image = await page.render(width: 2048, height: 2048);
if (image != null) {
final byteData = image.bytes;
final file = File('${(await getTemporaryDirectory()).path}/barcodes');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
String? barcode = await Scan.parse(file.path);
if (barcode == null) {
print("barcode not found in page $pageIndex");
} else {
print("Barcode Found: $barcode in page $pageIndex");
}
}
}
}

Set min/max screen size in Flutter windows

I am developing a Windows flutter application. The app has already mobile versions and I am converting to windows. The mobile design is already there but I need to convert it to windows and the problem is the design is not ready yet.
For this reason, I have been given a task to find out how to give maximum width and height for the application so that the user cannot change the app screen size using the mouse.
Is there a way to implement this on Flutter windows?
Yes, this can be done and it also avoids the problem mentioned by #Khamidjon Khamidov. To achieve this, you will need to make changes in 3 files:
pubspec.yaml
main.cpp (at windows\runner\main.cpp)
main.dart
Add the code below to your pubspec.yaml, under dependencies and save the file.
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding
path: plugins/window_size
Change the code below in main.cpp:
Win32Window::Size size(1280, 720);
to
Win32Window::Size size(min_width, min_height)
The above code will ensure your app startup at the preferred size. Replace min_width and min_height with either your minimum or maximum value pair.
Modify your main.dart as show below:
void main() {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
setWindowTitle('My App');
setWindowMaxSize(const Size(max_width, max_height));
setWindowMinSize(const Size(min_width, min_height));
}
runApp(const MyApp());
}
Replace max_width, max_height, min_width and min_height with your preferred value.
Note:
If you want a non-sizable form use the same min and max values.
METHOD 1
As #Stefano mentioned, I could use this library:
dependencies:
window_size:
git:
url: git://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:window_size/window_size.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isWindows) {
setWindowMaxSize(const Size(1024, 768));
setWindowMinSize(const Size(512, 384));
Future<Null>.delayed(Duration(seconds: 1), () {
setWindowFrame(Rect.fromCenter(center: Offset(1000, 500), width: 600, height: 1000));
});
}
runApp(MyApp());
}
But the problem here is that the window size is being set to default so it is changing its size after few seconds.
METHOD 2
Because, the first method didn't work as I expected I mixed the both methods:
In main.dart:
void main() {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isWindows) {
setWindowMaxSize(const Size(1024, 768));
setWindowMinSize(const Size(512, 384));
}
runApp(MyApp());
}
In lib/windows/runner/win32_window.cpp:
// this method already exists inside the file
bool Win32Window::CreateAndShow(const std::wstring& title,
const Point& origin,
const Size& size) {
Destroy();
const wchar_t* window_class =
WindowClassRegistrar::GetInstance()->GetWindowClass();
const POINT target_point = {static_cast<LONG>(/*x // change here to move to center*/ 550), // before -> origin.x
static_cast<LONG>(/*y // change here to move vertically*/ origin.y)}; // before -> origin.y
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
double scale_factor = dpi / 96.0;
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE,
Scale(/* x // move to center */ 550, scale_factor), Scale(/* y // move screen vertically */ origin.y, scale_factor),// before -> origin.x, origin.y
Scale(/* width // set default width */ 450, scale_factor), Scale(/* height // set default height */ 800, scale_factor), // before -> size.width, size.height
nullptr, nullptr, GetModuleHandle(nullptr), this);
if (!window) {
return false;
}
return OnCreate();
}
Yes, we can limit the size of a Windows Flutter app by using the window_size package.
To use it in our app, we need to add it in our pubspec.yaml dependencies:
dependencies:
flutter:
sdk: flutter
window_size:
git:
url: git://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
And use it at initialization as follows below:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:window_size/window_size.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isWindows) {
setWindowMaxSize(const Size(1024, 768));
setWindowMinSize(const Size(512, 384));
}
runApp(MyApp());
}
You can use this Plugin to add the ability to control your window instance.
Installation
add this your your pubspec.yaml :
dependencies:
window_manager: ^0.2.7
Usage
in your main() method add this :
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await windowManager.ensureInitialized();
if (Platform.isWindows) {
WindowManager.instance.setMinimumSize(const Size(1200, 600));
WindowManager.instance.setMaximumSize(const Size(1200, 600));
}
runApp(MyApp());
}
and replace 1200, and 600 with your preferred size.
You can use methods like this, without additional packages. This is an example of setting the minimum window size:
await MethodChannel('desktop_window').invokeMethod('setMinWindowSize', {'width': 500, 'height': 800});

PyQt5 - Update an Image in QML

I have been looking for a way to update images on my QML UI from my PyQt code. The closest answer I could find was from Grecko Update ImageView in QML
// Code from Stackoverflow Link
// MyImage.qml
Image {
cache: false
function reload() {
var tmpSource = source;
source = "";
source = tmpSource;
}
}
I would like to apply that solution (or any solution) to my project. Below is some sample code that is similar to my implementation.
#test.py
import sys
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlApplicationEngine
if __name__ == '__main__':
myApp = QApplication(sys.argv)
engine = QQmlApplicationEngine()
context = engine.rootContext()
context.setContextProperty("main", engine)
engine.load('main.qml')
win = engine.rootObjects()[0]
image = win.findChild(QObject, "myimage")
#What do with the image here?
win.show()
sys.exit(myApp.exec_())
Here is the QML code.
//test.qml
Image {
id: image1
objectName: "myimage"
x: 384
y: 403
width: 100
height: 100
source: ""
}
I am still fairly new to PyQT5 and QML so if someone has a basic example that shows how I can implement this or can edit my basic example, it would be greatly appreciated.
Thank you :)
If you want to reload all images via your MyImage type, then one option is to use the setContextProperty() mechanism to expose an Python object with a signal and use that signal in MyImage.qml to trigger the reload() function.
In Python:
reloader = ObjectWithAReloadSignal()
context.setContextProperty("_reloader", reloader);
in MyImage.qml
Image {
id: image
void reload() { ... }
Connections {
target: _reloader
onReloadImages: image.reload()
}
}
The assumption here is that the ObjectWithAReloadSignal has a signal called reloadImages() which ti emits when QML should trigger the reload.

Haxe Type Not Found

I'm trying to run the most basic Haxe program but keep getting errors.
The Main.hx file looks like this:
package;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.Lib;
import flixel.FlxGame;
import flixel.FlxState;
class Main extends Sprite {
var gameWidth:Int = 640; // Width of the game in pixels (might be less / more in actual pixels depending on your zoom).
var gameHeight:Int = 480; // Height of the game in pixels (might be less / more in actual pixels depending on your zoom).
var initialState:Class<FlxState> = MenuState; // The FlxState the game starts with.
var zoom:Float = -1; // If -1, zoom is automatically calculated to fit the window dimensions.
var framerate:Int = 60; // How many frames per second the game should run at.
var skipSplash:Bool = false; // Whether to skip the flixel splash screen that appears in release mode.
var startFullscreen:Bool = false; // Whether to start the game in fullscreen on desktop targets
// You can pretty much ignore everything from here on - your code should go in your states.
public static function main():Void
{
Lib.current.addChild(new Main());
}
public function new()
{
super();
if (stage != null)
{
init();
}
else
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function init(?E:Event):Void
{
if (hasEventListener(Event.ADDED_TO_STAGE))
{
removeEventListener(Event.ADDED_TO_STAGE, init);
}
setupGame();
}
private function setupGame():Void
{
var stageWidth:Int = Lib.current.stage.stageWidth;
var stageHeight:Int = Lib.current.stage.stageHeight;
if (zoom == -1)
{
var ratioX:Float = stageWidth / gameWidth;
var ratioY:Float = stageHeight / gameHeight;
zoom = Math.min(ratioX, ratioY);
gameWidth = Math.ceil(stageWidth / zoom);
gameHeight = Math.ceil(stageHeight / zoom);
}
addChild(new FlxGame(gameWidth, gameHeight, initialState, zoom, framerate, framerate, skipSplash, startFullscreen));
}
}
Just the generic template file. When I run it in Terminal (running Mac OS X El Capitan), I get this error:
Main.hx:8: characters 7-21 : Type not found : flixel.FlxGame
Haven't had problems with the installations or anything and I am new to Haxe so I don't know where to start. Any ideas?
Thanks :)
Did you add the library when you try to run your game ?
You can do that by using the command line haxe -lib flixel -main Main ....
Or by writting an hxml file containing all your CLI arguments :
-lib flixel
-main Main
Update after #Gama11 comment :
HaxeFlixel used the OpenFL format for the compilation information (see http://www.openfl.org/documentation/projects/project-files/xml-format/).
So you should include include flixel library using : <haxelib name="flixel" />in your Project.xml file.

Animate a SVG Element with Dart

I'd like to animate a SVG Element using Dart. That is slowly moving a RectElement of the "dart:svg" package from one y-coordinate to another. Unfortunately I couldn't find an example. I also tried to use the animation package found here here but it seems not to work with SVG elements.
You can achieve this by using animation frames and updating the y attribute (keeping in mind that it is a string):
import 'dart:html';
import 'dart:svg';
import 'dart:async';
RectElement rect;
int pos = 0;
int dest = 300;
void main() {
// Get a reference to the element
rect = query("#rect");
// Start the animation
window.animationFrame.then(animate);
}
void animate(num delta) {
// Keep moving the element down until we reach the destination
if(pos < dest) {
pos += 2;
rect.attributes['y'] = pos.toString();
// Continue the animation
window.animationFrame.then(animate);
}
}
Edit: Switched from timers to animation frames as per Greg Lowe's suggestion
I realize this question is old, however, some days ago I wrote an example about it in my blog.
This is using the pub package tweenengine
The steps are basically:
Creating an accessor for whatever svg element you are trying to animate
create a TweenManager
on your window.animation.then() call the tweenmanager's update.
I did create a gist for it as well.

Resources