在android studio ontap函数中 null错误


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)