Home > Software design >  _CastError - Null check operator used on a null value
_CastError - Null check operator used on a null value

Time:11-27

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

CodePudding user response:

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

CodePudding user response:

It is possible to get null value from reading map. while those variable already nullable, you can skip using !.

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

CodePudding user response:

There are two ways to do that which are described below

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

and you can also do like this

  setState(() {
          text = quotes[randomNumber]["text"] !=null ? quotes[randomNumber]["text"] : "";
          author = quotes[randomNumber]["author"] !=null ? quotes[randomNumber]["author"] : "";
          notifylisteners();
          });
  • Related