_CastError – Null check operator used on a null value

Issue

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() {}
}

Solution

You are call ! on a null value (which is quotes[randomNumber]["text"] and quotes[randomNumber]["author"] ), Change this:

setState(() {
  text = quotes[randomNumber]["text"]!;
  author = quotes[randomNumber]["author"]!;
  notifylisteners();
  
});

to this:

setState(() {
  text = quotes[randomNumber]["text"] ?? "";
  author = quotes[randomNumber]["author"] ?? "";
  notifylisteners();
  
});

Answered By – eamirho3ein

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *