![](/img/trans.png)
[英]How can we use the same instance of widget (with no rebuild) in a Navigator in flutter?
[英]How to create two same instance widget in Flutter
大家,我只是测试了Dart中的“const”和“new”关键字,我发现:如果我想创建完全相同的实例,我必须:
像这样:
class A {
final int x;
const A(this.x);
}
// when use
var a = const A(0);
var b = const A(0);
identical(a,b); // this is true, they are same instance
---------------------------- 好的,到目前为止,这还可以,但是,!!! ---------------------------- 当我还想创建两个相同的“小部件”时,我失败了!
像这样:
class A extends StatelessWidget {
final int x;
const A(this.x,{Key? key })
: super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
// when use
var a = const A(0);
var b = const A(0);
identical(a,b); // this is false!!!!!! why?????????
所以....有人可以告诉我如何创建两个相同的实例小部件? 谢谢。 :)
欢迎来到 SOF。
这是因为 Dart 首先实例化一个 A 然后使其成为常数,请不要将常数与static
混淆。
第一个示例给出相同=真的原因是因为两个对象具有相似的hashCode
。 ( https://api.dart.dev/stable/2.10.5/dart-core/Object/hashCode.html )
hashCode 用于 object 比较操作,例如 ==
你应该这样写,其实没用::
var z = const A(0);
var a = z;
var b = z
identical(a,b);
或者你应该覆盖 == 和 hashCode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.