flutter学习之NULL问题解决
flutter学习之NULL问题解决在flutter实战的第二章计数器实例学习和应用的过程中遇到两个null问题,这是直接复用原来的代码产生的,应该是后续的flutter版本升级对相关调用类构造方法添加了空判断导致的。计数器实例代码import 'package:flutter/material.dart';class Study extends StatelessWidget {@overrid
·
flutter学习之NULL问题解决
在flutter实战的第二章计数器实例学习和应用的过程中遇到两个null问题,这是直接复用原来的代码产生的,应该是后续的flutter版本升级对相关调用类构造方法添加了空判断导致的。
计数器实例代码
import 'package:flutter/material.dart';
class Study extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "The First Flutter App",
theme: new ThemeData(
primaryColor: Colors.red,
),
home: new MyHomePage(title: "This is MyHomePage"),
);
}
}
class MyHomePage extends StatefulWidget {
//此处报错
//此处报错
//此处报错
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text("please click the button"),
new Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: "增加",
child: new Icon(Icons.add),
),
);
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
}
报错内容
Error: The parameter 'key' can't have a value of 'null' because of its type 'Key', but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
MyHomePage({Key key, this.title}) : super(key: key);
^^^
Error: The parameter 'title' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
MyHomePage({Key key, this.title}) : super(key: key);
报错修改
我们可以用官方推荐的修改方式修改即Key ?key来表示可空,又因为title是final修饰量,final修饰的常量必须在声明进初始化或者在构造函数中初始化,它的值可以动态计算。 所以可以添加required修饰要求必须作为参数填入。
MyHomePage({Key?key,required this.title}) : super(key: key);
运行效果
更多推荐
已为社区贡献4条内容
所有评论(0)