我正在做一门关于Udacity Flutter的课程。对于某些作业,我正在学习如何创建小部件。来自C /Python,我完全不了解此类构造函数语法。
所以我的主。dart包含一个类别的小部件(我正在构建的小部件(,内部的小部件内部。我正在从main.dart文件中传递3个参数,但我不明白什么
const类别({...}(:...;
部分正在做。
这是我的类别的方式:
import 'package:flutter/material.dart';
class Category extends StatelessWidget {
final String name;
final ColorSwatch color;
final IconData iconLocation;
const Category({
Key key,
@required this.name,
@required this.color,
@required this.iconLocation,
}) : assert(name != null),
assert(color != null),
assert(iconLocation != null),
super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: 100.0,
padding: EdgeInsets.all(8.0),
child: InkWell(
borderRadius: BorderRadius.circular(25.0),
splashColor: color,
onTap: () {
print('i am cool');
},
child: Row(
children: <Widget>[
Padding(
padding: EdgeInsets.all(16.0),
child: Icon(
iconLocation,
size: 60.0,
),
),
Text(
'Length',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 24.0,
),
),
],
),
),
);
}
}
您在C ,Python或Java中看不到几种DART特定的语言功能。您可以在DART文档中阅读有关所有内容的更多信息。
命名参数
在Python中,每个论点都可能命名。在DART中,只能在构造函数呼叫中的名称中引用卷曲括号中包裹的论点。因此,将卷曲括号围绕在参数周围,使我们在呼叫者方面很好看:
Category(
something: ...
somethingElse: ...
)
初始化列表
初始化列表位于构造函数签名和身体之间。它在身体面前跑。在那里,您可以初始化实例变量,主张事物并调用超级。
您可能会问,为什么我们不能在构造体的主体中做这些事情?看看下一个功能:
常数表达式
如果构造函数满足多个要求,则可以将构造函数标记为恒定(例如,它没有构造函数主体,并且类只有最终字段(。这些附加要求允许对构造函数的调用标记为const
,从而导致构造函数在编译时而不是在运行时运行。如果您经常重复使用特定实例(例如,例如EdgeInsets.all(16)
(,则所有实例将共享相同的内存位置。因此,标记为const
的构造函数允许将类直接嵌入到由此结果的程序的记忆中。
我从未编码飞镖。但这看起来与Java构造函数非常相似。
class Category extends StatelessWidget {
final String name;
final ColorSwatch color;
final IconData iconLocation;
const Category({
Key key,
@required this.name,
@required this.color,
@required this.iconLocation,
}) : assert(name != null),
assert(color != null),
assert(iconLocation != null),
super(key: key);
构造函数通常用于初始化类属性(除其他外(。这是进行三个参数,我假设DART会自动分配具有匹配名称与相应类属性的构造函数。它还具有一些验证规则,例如名称!= null等。