在“示例”页面上,有一个名为“将数据发送到新屏幕”的项目。我对第65行的构造函数有疑问。
// In the constructor, require a Todo
DetailScreen({Key key, @required this.todo}) : super(key: key);
什么是超级(键:键)?请给我整个行的解释。代码在这里。
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Todo {
final String title;
final String description;
Todo(this.title, this.description);
}
void main() {
runApp(MaterialApp(
title: 'Passing Data',
home: TodosScreen(
todos: List.generate(
20,
(i) => Todo(
'Todo $i',
'A description of what needs to be done for Todo $i',
),
),
),
));
}
class TodosScreen extends StatelessWidget {
final List<Todo> todos;
TodosScreen({Key key, @required this.todos}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Todos'),
),
body: ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todos[index].title),
// When a user taps on the ListTile, navigate to the DetailScreen.
// Notice that we're not only creating a DetailScreen, we're
// also passing the current todo through to it!
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(todo: todos[index]),
),
);
},
);
},
),
);
}
}
class DetailScreen extends StatelessWidget {
// Declare a field that holds the Todo
final Todo todo;
// In the constructor, require a Todo
DetailScreen({Key key, @required this.todo}) : super(key: key);
@override
Widget build(BuildContext context) {
// Use the Todo to create our UI
return Scaffold(
appBar: AppBar(
title: Text("${todo.title}"),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text('${todo.description}'),
),
);
}
}
构造函数有两个命名参数。
默认情况下,命名参数是可选的。
@required
是Dart分析器识别的注释,如果在构建时调用时未通过,则会产生警告(在运行时无效)。
:
启动“初始化程序列表”,即在超类的构造函数之前执行的表达式的逗号分隔列表,因此也在构造函数主体之前执行。
它通常用于使用断言检查参数值以及使用计算值初始化最终字段。
局限性在于,表达式无法读this.
(隐式或显式)访问,因为在执行超级构造函数之前对象初始化未完成。
如果省略,则初始化程序中的最后一个元素是对父类的默认构造函数的隐式调用,如果给定,则是对当前类或父类的特定构造函数的调用。
在您问题的示例中,key
传递给构造函数的参数将转发到key
超类的未命名构造函数的命名参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句