问题
I want to use those basic classes (such as Offset
, Size
, and Color
), in a pure-dart
program. I cannot import them in a pure dart project. How can I use them?
Those classes are really fundamental and quite helpful. For example, with Color
(and Colors
) the color system can be easily used. So I would appreciate it if I could use them.
I have tried this, but it gives me the following error: Error: Not found: 'dart:ui'
. I have also tried copying and pasting, but that is a bit ugly...
回答1:
Well in short, you can't, unless you copy the code from the source class in package:flutter/material.dart
.
回答2:
You can't import dart:ui
in a console program. But you can make a few things if you want to use them:
To use a Color
class, along with RgbColor
, HexColor
, HslColor
, XyzColor
and CielabColor
, you can use the color
package. You can use it in a cli app by importing the package in the pubspec.yaml file (which you need to manually create)
pubspec.yaml:
name: CLI
description: A CLI App
version: 1.0.0
publish_to: 'none'
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
color: 2.1.1 <---
main.dart:
import 'package:color/color.dart';
void main(List<String> args) {
Color color = new Color.hex("FFFFFF");
print(color); //Should print "ffffff"
}
Edit: If you want to use Flutter's Color
class, copy it into a separate color.dart
file, as well as _scaleAlpha()
found in the same file as the Color
class (sky_engine\lib\ui\painting.dart
), and _clampInt()
+ _lerpInt()
(found in sky_engine\lib\ui\lerp.dart
). Don't forget to import "dart:math" as math
to this new file. You said it was ugly to just copy, but it is the best you can do if you want to make this compatible with Flutter later. Just change import "color.dart"
in your main.dart
file to import "dart:ui"
As for Size
and Offset
, they are located in (path to flutter) flutter\bin\cache\pkg\sky_engine\lib\ui\geometry.dart
. As you've said, copying and pasting is ugly, and looking at the functions I'd say most are not useful for a console app.
Maybe try to implement them yourself by writing these classes from scratch fit for your needs, or by stripping down the original classes in geometry.dart
. Both classes are quite small if you remove the comments.
来源:https://stackoverflow.com/questions/65914605/use-basic-classes-like-offset-color-in-dart-without-flutter