官方demo如下
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'InkWell Demo';
return new MaterialApp(
title: title,
home: new MyHomePage(title: title),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(title),
),
body: new Center(child: new MyButton()),
);
}
}
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
// The InkWell Wraps our custom flat button Widget
return new InkWell(
// When the user taps the button, show a snackbar
onTap: () {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text('Tap'),
));
},
child: new Container(
padding: new EdgeInsets.all(12.0),
child: new Text('Flat Button'),
),
);
}
}
运行报错
Xcode's output:
↳
lib/main.dart:20:19: Error: The parameter 'key' can't have a value of 'null' because of its type 'Key', but the implicit default value is 'null'.
- 'Key' is from 'package:flutter/src/foundation/key.dart' ('../../flutter/packages/flutter/lib/src/foundation/key.dart').
Try adding either an explicit non-'null' default value or the 'required' modifier.
MyHomePage({Key key, this.title}) : super(key: key);
^^^
lib/main.dart:20:29: 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);
^^^^^
Failed to package /Users/wangweiwei/Downloads/readme.
Command PhaseScriptExecution failed with a nonzero exit code
note: Using new build system
note: Planning
note: Build preparation complete
note: Building targets in parallel
原因:
demo的flutter版本过老,新的flutter版本升级对相关调用类构造方法添加了空判断导致
解决:
根据报错提示进行调整。可以用Key ?key来表示可空,又因为title是final修饰量,final修饰的常量必须在声明进初始化或者在构造函数中初始化,它的值可以动态计算。 所以可以添加required修饰要求必须作为参数填入。
MyHomePage({Key? key, required this.title}) : super(key: key);
网友评论