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);
運行效果

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/287434.html
標籤:區塊鏈
