import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:safehandsv2/utils/quotes.dart';
class CustomAppBar extends StatelessWidget {
//const CustomAppBar({super.key});
Function? onTap;
int? quoteIndex;
CustomAppBar({this.onTap, this.quoteIndex});
@override
Widget build(BuildContext context) {
return InkWell(
onTap:() {
**onTap!();**
},
child: Text(sweetSayings[quoteIndex!],
style: TextStyle(fontSize: 22, ),
),
);
}
}
所以这里我得到的错误是null未定义等等
error - Exception has occurred.
_CastError (Null check operator used on a null value)
您的函数onTap
定义为可空(?
):
Function? onTap;
则使用!
操作符调用函数,这意味着说"我不会为空";但是当你调用它时,它实际上是null
onTap: () {
if (onTap != null) {
onTap!();
}
},
当你调用CustomAppBar
时,你可能没有传入onTap
,因为它是可选的。
参见
- 理解"! ";空格操作符
- 了解null安全(part .dev)