我有一个简单的应用程序,它通过CustomPainter画布上的红色或绿色圆圈进行绘制,具体取决于按下的按钮AppBar:
该类ColorCircle扩展CustomPainter并负责绘制彩色圆圈:
class ColorCircle extends CustomPainter {
MaterialColor myColor;
ColorCircle({@required this.myColor});
@override
void paint(Canvas canvas, Size size) {
debugPrint('ColorCircle.paint, ${DateTime.now()}');
final paint = Paint()..color = myColor;
canvas.drawCircle(Offset(size.width / 2, size.height / 2), 100, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
Run Code Online (Sandbox Code Playgroud)
不同颜色的绘制效果很好,但是当我单击(仅一次!)或将鼠标悬停在其中一个按钮上时,该paint方法会被调用多次:
进一步的实现细节:我使用 aStatefulWidget来存储actualColor. 在 build 方法中actualColor传递给ColorCircle构造函数:
class _MyHomePageState extends State<MyHomePage> {
MaterialColor actualColor = Colors.red;
@override
Widget build(BuildContext context) { …Run Code Online (Sandbox Code Playgroud) 我想用通用回调定义一个冻结类 [https://pub.dev/packages/freezed]。
冷冻类:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'foo.freezed.dart';
@freezed
abstract class Foo<T> with _$Foo {
factory Foo({
// String Function() callBackOne,
String Function(T) callBackTwo,
}) = _Foo;
}
Run Code Online (Sandbox Code Playgroud)
使用 Freezed 类的小部件:
class MyHomePage extends StatelessWidget {
// final fooOne = Foo<int>(callBackOne: () => 'Result: 42');
final fooTwo = Foo<int>(callBackTwo: (value) => 'Result: ${value * 3}');
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(fooTwo.callBackTwo(14)),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
lib/foo.freezed.dart:128:26: Error: The return type of the method '_Foo.callBackTwo' is …Run Code Online (Sandbox Code Playgroud) 您如何处理以下情况:
void main() {
print(getInt('d'));
}
Map<String, int> myMap = {'a':1, 'b':2, 'c':3};
int getInt(String key) {
if (!myMap.containsKey(key)) {
myMap[key] = 0;
}
return myMap[key]!;
}
Run Code Online (Sandbox Code Playgroud)
myMap[key]永远不会为空,但如果我删除 of ,!则会return myMap[key]!;出现空安全错误:
“int”类型的值?无法从函数“getInt”返回,因为它的返回类型为“int”。
用 抛弃可空性是否正确!,或者是否有更干净的方法?
我的页面中有这个自定义路径
class TestPathPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..color = Colors.black;
var x = size.width;
var y = size.height;
print(x);
var path = Path()
..moveTo(x, y / 4)
..lineTo(x * 0.95, y / 4)
..lineTo(x * 0.95, y / 3)
..lineTo(x * 0.99, y / 3)
..lineTo(x * 0.99, y / 3.7)
..lineTo(x * 0.955, y / 3.7)
..lineTo(x * 0.955, y / 3.15)
..lineTo(x …Run Code Online (Sandbox Code Playgroud) 我想将故事项目实现为不同的小部件。就像这个例子一样:
在这张图片中,仅更改了图像,但我想将整个小部件更改为故事项目。
我尝试过story_view包。但是,在此包中只能添加图像和视频。还有其他图书馆吗?