flutter报错处理-三

The argument type ‘Null’ can’t be assigned to the parameter type ‘Key’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import 'dart:math';

import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({required Key? key, required this.title}) : super(key: key);
final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _number = 0;
void _incrementCounter() {
_number = Random().nextInt(100);
setState(() {});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: InfoWidget(
number: _number,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InfoChildWidget(),
InfoChildWidget(),
InfoChildWidget(),
],
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

// <!-- InfoWidget -->
class InfoWidget extends InheritedWidget {
final int number;

InfoWidget({required Key key, required this.number, @required child})
: super(key: key, child: child);

@override
bool updateShouldNotify(InfoWidget oldWidget) {
return number != oldWidget.number;
}

static InfoWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType();
}
}

// <!-- InfoChildWidget -->
class InfoChildWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final int? number = InfoWidget.of(context)?.number;
return Text("$number", style: TextStyle(color: Colors.amber, fontSize: 40));
}
}

第13行 MyHomePage 报错:The named parameter 'key' is required, but there's no corresponding argument.

第40行 InfoWidget 报错:The named parameter 'key' is required, but there's no corresponding argument. (命名参数 key 是必须的,但是没有对应的参数。)

这个错误的出现是因为用了required关键字。如果想传递一个空值作为 key,可以像这样改造构造函数:

MyWidget({Key? key}) : super(key: key);

第 19 行 改成:MyHomePage({Key? key, required this.title}) : super(key: key);

第 67、68 行 改成:InfoWidget({Key? key, required this.number, @required child}) : super(key: key, child: child);

文章作者: 夜行书生
文章链接: https://yexingshusheng.com/2022/04/flutter-bao-cuo-chu-li-san.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 夜行书生