问:构造方法为什么要使用const关键字?
答:const关键字是用来返回const对象给声明为const的参数赋值用的。
如果没有const关键字,则给声明为const的参数赋值时,会报错
Error: Cannot invoke a non-‘const’ constructor where a const expression is expected.
但是const构造方法并不总是返回const对象,当给声明为const或final的参数赋值时,
会返回一个const对象,如果是给可变参数赋值,则返回一个可变的对象。
示例一:
import 'package:flutter/material.dart';
class TestKey extends LocalKey {
//不能实例化const对象
TestKey() : super();
}
main() {
//给可变变量赋值
TestKey aKey = TestKey();
TestKey bKey = TestKey();
//判断是否同一个对象
if (identical(aKey, bKey)) {
print('identical $aKey , $bKey');
} else {
/// 会走到这里
print('not identical $aKey , $bKey');
}
}
示例二:
import 'package:flutter/material.dart';
class TestKey extends LocalKey {
const TestKey() : super();
}
main() {
//给const变量赋值
const TestKey aKeyConst = TestKey();
const TestKey bKeyConst = TestKey();
//判断是否同一个对象
if (identical(aKeyConst, bKeyConst)) {
/// 会走到这里
print('identical $aKeyConst , $bKeyConst');//同一对象
} else {
print('not identical $aKeyConst , $bKeyConst');
}
print("===============我是华丽的分割线==================");
//给可变变量赋值
TestKey aKey = TestKey();
TestKey bKey = TestKey();
//判断是否同一个对象
if (identical(aKey, bKey)) {
print('identical $aKey , $bKey');
} else {
/// 会走到这里
print('not identical $aKey , $bKey');//不同对象
}
}