skip to Main Content

i think i need help here. My code says error "Null Check Operator Used on A null Value". When i running/build the app for first time everything is oke. The apk running goodly. But when me click home button or refresh the TextSpan recognizer, the null check alert is showing. Can you see the code below and give me the solution for this problem issue. Sorry if my english bad, i hope you understand the problem guys. PLSS HELP 🙂

import 'dart:async';
import 'dart:convert';
import 'package:adhan/adhan.dart';
import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:geocoding/geocoding.dart' as MyLocation;
import 'package:get/get.dart';
import 'package:hijri/hijri_calendar.dart';
import 'package:location/location.dart';
import 'package:intl/intl.dart';
import 'package:muslimapk/pages/kiblat_page.dart';


class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int currentIndexPage = 0;
  String locale = 'id';
  final location = new Location();
  String? locationError, _timenow, _datenow, _tglHijriah, _hari;
  String? MylocationCountry, MylocationCity , shalatTime ;
  PrayerTimes? prayerTimes;
  double? latitude, longitude, pLat, pLong;
  HijriCalendar? _todayhijr;


  @override
  void initState() {
    _todayhijr = HijriCalendar.now();
    _tglHijriah = _todayhijr!.toFormat("MMMM, dd yyyy H");
    _timenow = "${DateTime.now().hour} : ${DateTime.now().minute} }";
    Timer.periodic(Duration(seconds:1), (Timer t)=>_getCurrentTime());


    if (DateTime.now().hour >= 05 && DateTime.now().hour <= 06) {
      shalatTime = "Subuh";
    }if (DateTime.now().hour >= 06 && DateTime.now().hour <= 07) {
      shalatTime = "Matahari Terbit";
    }if (DateTime.now().hour >= 12 && DateTime.now().hour <= 15) {
      shalatTime = "Dzuhur";
    }if (DateTime.now().hour >= 15 && DateTime.now().hour <= 18) {
      shalatTime = "Ashar";
    }if (DateTime.now().hour >= 18 && DateTime.now().hour <= 20) {
      shalatTime = "Maghrib";
    }if (DateTime.now().hour >= 20 && DateTime.now().hour <= 05) {
      shalatTime = "Isya";
    }

    getLocationData().then((locationData) async {
      if (!mounted) {
        return;
      }
      if (locationData != null)  {

        setState(() {
          prayerTimes = PrayerTimes(
              Coordinates(locationData.latitude, locationData.longitude),
              DateComponents.from(DateTime.now()),
              CalculationMethod.karachi.getParameters());
          pLat = prayerTimes!.coordinates.latitude;
          pLong = prayerTimes!.coordinates.longitude;
          print("Latitude : $pLat, Longitude : $pLong");
        });
      } else {
        setState(() {
          locationError = "Couldn't Get Your Location!";
        });
      }
      List<MyLocation.Placemark> placemarks = await MyLocation.placemarkFromCoordinates(pLat!, pLong!);
      setState(() {

        MylocationCountry = placemarks.reversed.last.country.toString();
        MylocationCity = placemarks.reversed.last.locality.toString();
        print("Country : $MylocationCountry, City : $MylocationCity");
        print("Tanggal hijriah : $_todayhijr");
        print("Time Now : $_timenow");
      });
    });

    //DateTime.now().hour >= 18 && DateTime.now().hour <= 19

    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    HijriCalendar.setLocal(locale);
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(225),
        child: AppBar(
          automaticallyImplyLeading: false,
          title: Builder(
              builder: (BuildContext context) {
                final prayerTimes = this.prayerTimes;
                if (prayerTimes != null) {
                  return RichText(
                      text: TextSpan(
                        text: MylocationCountry ?? "NULL",
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.of(context).pushNamed('/home');
                          },
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w500,
                        ),
                          children: [
                            TextSpan(
                              text: "n$MylocationCity" ,
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.of(context).pushNamed('/home');
                                },
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                            WidgetSpan(
                              alignment: PlaceholderAlignment.middle,
                              child: Icon(
                                Icons.refresh_rounded,
                                color: Colors.white,
                              )

                            ),
                          ],
                      )

                  );
                }
                if (locationError != null) {
                  return Text(locationError!);
                }
                return CircularProgressIndicator(
                  color: Colors.white,
                );
              }
          ),
          flexibleSpace: ClipRect(
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("lib/images/masjidil-aqsha.jpg"),
                  fit: BoxFit.fill,
                  colorFilter: ColorFilter.mode(
                      Color(0xFF002700).withOpacity(0.50), BlendMode.darken)
                ),
              ),
            ),
          ),
          bottom: PreferredSize(
            preferredSize: Size.fromHeight(200),
            child: Column(
            children: [
              Text(shalatTime ?? "NULL",
                style: TextStyle(
                    fontSize: 24,
                    color: Colors.white),),
             SizedBox( height: 10 ),
              Text(_timenow ?? "NULL",
                style: TextStyle(
                    fontSize: 40,
                    color: Colors.white),),
              SizedBox( height: 10 ),
              Text( _tglHijriah ?? "NULL",
                style: TextStyle(
                    fontSize: 24,
                    color: Colors.white),),
              SizedBox( height: 10 ),
            ],
            ),
          ),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(0),
                  bottomRight: Radius.circular(0))
          ),
          actions: <Widget>[
            Container(
              margin: EdgeInsets.all(10),
              height: 250,
              child: RichText(
                text: TextSpan(
                  text: "$_datenow",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                  children: [
                    TextSpan(
                      text: "n$_hari",
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ],
                )
              ))],
        ),
      ),

      extendBodyBehindAppBar: false,

      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Builder(
              builder: (BuildContext context) {
                final prayerTimes = this.prayerTimes;
                if (prayerTimes != null) {
                  return Column(
                    children: [
                      Text(
                        'Prayer Times for Today',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.white),
                      ),
                      Text('Fajr Time: ' +
                          DateFormat("HH:mm").format(prayerTimes.fajr),
                          style: TextStyle(color: Colors.white),),
                      Text('Sunrise Time: ' +
                          DateFormat("HH:mm").format(prayerTimes.sunrise),
                          style: TextStyle(color: Colors.white),),
                      Text('Dhuhr Time: ' +
                          DateFormat("HH:mm").format(prayerTimes.dhuhr),
                          style: TextStyle(color: Colors.white),),
                      Text('Asr Time: ' +
                          DateFormat("HH:mm").format(prayerTimes.asr),
                          style: TextStyle(color: Colors.white),),
                      Text('Maghrib Time: ' +
                          DateFormat("HH:mm").format(prayerTimes.maghrib),
                          style: TextStyle(color: Colors.white),),
                      Text('Isha Time: ' +
                          DateFormat("HH:mm").format(prayerTimes.isha),
                          style: TextStyle(color: Colors.white),),
                    ],
                  );
                }
                if (locationError != null) {
                  return Text(locationError!);
                }
                return CircularProgressIndicator(
                  color: Colors.white,
                );
              },
            )
          ],
        ),
      ),

      bottomNavigationBar: ConvexAppBar(
          style: TabStyle.react,
          backgroundColor: Color(0xFF018700),
          top: -20,
          items: [
            TabItem(icon: Icons.home, title: 'Beranda'),
            TabItem(icon: Icons.navigation, title: 'Kiblat'),
            TabItem(icon: Icons.calendar_month, title: 'Kalender'),
            TabItem(icon: Icons.settings, title: 'Pengaturan'),
          ],
          initialActiveIndex: currentIndexPage,
          onTap: (int index) {
            currentIndexPage = index;
            if(index == 0) {
              Navigator.of(context).pushNamed('/home');
            }
            if(index == 1) {
              Navigator.of(context).pushNamed('/kiblat');
            }
            if(index == 2) {
              Navigator.of(context).pushNamed('/calendar');
            }
            if(index == 3) {
              Navigator.of(context).pushNamed('/settings');
            }
          }
      ),
    );
  }

  Future<LocationData?> getLocationData() async {
    var _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return null;
      }
    }

    var _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return null;
      }
    }

    return await location.getLocation();
  }

  void _getCurrentTime()  {
    setState(() {
      _timenow = DateFormat('hh:mm').format(DateTime.now());
      _datenow = DateFormat.yMMMMd("id").format(DateTime.now().toLocal());
      _hari    = DateFormat.EEEE("id").format(DateTime.now());
    });
  }
}

I have tried to make checknull with "!" but the alert still showing. This happened when i go or refresh the home route.

2

Answers


  1. Chosen as BEST ANSWER

    I got the problem clearly. The solution is I put the var hijri to below Widget Build like this :

      @override
      Widget build(BuildContext context) {
        HijriCalendar.setLocal('en');
        var _hijrCalendar = HijriCalendar.now();
    

    thank you so much for everyone who tried to help me.


  2. It most likely goes wrong on this line

      List<MyLocation.Placemark> placemarks = await MyLocation.placemarkFromCoordinates(pLat!, pLong!);
    

    Your code will come there even when pLat and pLong are null. This happens when locationData is null. I believe you would actually like to exit the function when that happens so you need to return in the end of the else like this:

          if (locationData != null)  {
    
            setState(() {
              prayerTimes = PrayerTimes(
                  Coordinates(locationData.latitude, locationData.longitude),
                  DateComponents.from(DateTime.now()),
                  CalculationMethod.karachi.getParameters());
              pLat = prayerTimes!.coordinates.latitude;
              pLong = prayerTimes!.coordinates.longitude;
              print("Latitude : $pLat, Longitude : $pLong");
            });
          } else {
            setState(() {
              locationError = "Couldn't Get Your Location!";
            });
            return; //ADD THIS
          }
    

    Without it your code just continues below it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search