I get this error when I run my flutter App. I’ve not been able to figure out why this error keeps occurring.
Error:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following _CastError was thrown building
RawGestureDetector-[LabeledGlobalKey#3c378](state:
RawGestureDetectorState#d987a(gestures: , behavior: opaque)):
Null check operator used on a null value
My code:
import './quotes.dart';
import 'dart:math';
import '../constants.dart';
class HadithQuotes extends StatefulWidget {
const HadithQuotes({Key? key}) : super(key: key);
@override
State<HadithQuotes> createState() => _HadithQuotesState();
}
class _HadithQuotesState extends State<HadithQuotes> {
String? text = "";
String? author = "";
setQuote() {
int randomNumber = Random().nextInt(quotes.length);
setState(() {
text = quotes[randomNumber]["text"]!;
author = quotes[randomNumber]["author"]!;
notifylisteners();
});
}
@override
initState() {
setQuote();
super.initState();
}
@override
Widget build(BuildContext context) {
return
Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
child: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.green.withOpacity(0.9),
kGoodOrange,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
color: kGoodOrange,
borderRadius: BorderRadius.circular(8)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [ Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(25.0),
child: Text(
text ?? '',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.white,
),
),
),
Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
author?? '',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.white,
),
),
),
Row(
children: [
Column(
children: [
TextButton(
onPressed: setQuote,
child: Image.asset(
'assets/images/next.png',
width: 25,
),
),
],
),
],
),
],
)
],
),
)
),
);
}
void notifylisteners() {}
}
3
Answers
It is possible to get null value from reading map. while those variable already nullable, you can skip using
!
.You are call
!
on anull
value (which isquotes[randomNumber]["text"]
andquotes[randomNumber]["author"]
), Change this:to this:
There are two ways to do that which are described below
and you can also do like this