iamriajul / adhan-dart

Adhan for Dart / Muslim Prayer Times Library. Now retrieving Prayer time in Dart easier than ever.
https://pub.dev/packages/adhan
MIT License
86 stars 41 forks source link

LateInitializationError: Field 'prayerTimes' has not been initialized. #43

Closed shaadart closed 1 year ago

shaadart commented 1 year ago

Assalamu Alaykum : ) May there be peace upon you.

The adhan-dart is very cheering, empowering, and an excellent means to serve the nation. I am glad and thankful to Allah that I came across the package. And I would like to cheer up the team who worked on it!

I am having trouble setting up the adhan-dart.

So, What I have done:

  1. in the main. dart I am using the widget PrayerTimings()
  2. I created another file named, prayer.dart where the main prayer timing widget is placed.

I am posting down my main.dart and prayer.dart file with the errors. I will feel elevated to be helped.

shaadart commented 1 year ago

main.dart

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter',
      theme: ThemeData(
          textTheme: GoogleFonts.workSansTextTheme(),
          primaryTextTheme: GoogleFonts.courierPrimeTextTheme(),
          useMaterial3: true,
          colorScheme: const ColorScheme.light(
            primary: Color(0xff000E3F),
          )
          // colorScheme: ColorScheme.fromSeed(
          //   secondary: const Color(0xffFF96E2),
          //   seedColor: const Color(0xff000E3F),
          // )
          ),
      home: const MyHomePage(title: 'Keer'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [PrayerTimings()],
      ),
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            icon: const Icon(CarbonIcons.search),
            onPressed: () {
              // do something
            },
          )
        ],
      ),

      floatingActionButton: FloatingActionButton(
          onPressed: (){},
          child: const Icon(PhosphorIcons
              .arrow_right)), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
shaadart commented 1 year ago

prayer.dart

import 'package:adhan/adhan.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:location/location.dart';

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

  @override
  State<PrayerTimings> createState() => _PrayerState();
}

class _PrayerState extends State<PrayerTimings> {
  final location = Location();
  late String locationError;
  late PrayerTimes prayerTimes;

  @override
  void initState() {
    getLocationData().then((locationData) {
      if (!mounted) {
        return;
      }
      if (locationData != null) {
        setState(() {
          prayerTimes = PrayerTimes(
              Coordinates(locationData.latitude!, locationData.longitude!),
              DateComponents.from(DateTime.now()),
              CalculationMethod.karachi.getParameters());
        });
      } else {
        setState(() {
          locationError = "Couldn't Get Your Location!";
        });
      }
    });

    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Builder(
        builder: (BuildContext context) {
          if (prayerTimes != null) {
            return Column(
              children: [
                const Text('Prayer Times for Today',
                    textAlign: TextAlign.center),
                Text('Fajr Time: ${DateFormat.jm().format(prayerTimes.fajr)}'),
                Text(
                    'Sunrise Time: ${DateFormat.jm().format(prayerTimes.sunrise)}'),
                Text(
                    'Dhuhr Time: ${DateFormat.jm().format(prayerTimes.dhuhr)}'),
                Text('Asr Time: ${DateFormat.jm().format(prayerTimes.asr)}'),
                Text(
                    'Maghrib Time: ${DateFormat.jm().format(prayerTimes.maghrib)}'),
                Text('Isha Time: ${DateFormat.jm().format(prayerTimes.isha)}'),
              ],
            );
          }
          if (locationError != null) {
            return Text(locationError);
          }
          return const Text('Waiting for Your Location...');
        },
      ),
    );
  }
}
shaadart commented 1 year ago

error

Restarted application in 7,054ms.

════════ Exception caught by widgets library ═══════════════════════════════════
The following LateError was thrown building Builder(dirty):
LateInitializationError: Field 'prayerTimes' has not been initialized.

The relevant error-causing widget was
Builder
package:unique/cards/prayer.dart:66
When the exception was thrown, this was the stack
#0      _PrayerState.prayerTimes (package:unique/cards/prayer.dart)
package:unique/cards/prayer.dart:1
#1      _PrayerState.build.<anonymous closure>
package:unique/cards/prayer.dart:68
#2      Builder.build
package:flutter/…/widgets/basic.dart:7371
#3      StatelessElement.build
package:flutter/…/widgets/framework.dart:4876
#4      ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4806
#5      Element.rebuild
package:flutter/…/widgets/framework.dart:4529
#6      ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:4787
#7      ComponentElement.mount
package:flutter/…/widgets/framework.dart:4781
...     Normal element mounting (44 frames)
iamriajul commented 1 year ago

Waalaikumussalam, The problem is not in the adhan-dart rather there's a bug in your code. To solve that make prayerTimes nullable.

class _PrayerState extends State<PrayerTimings> {
  ///...
  PrayerTimes? prayerTimes;
  ///...
}
shaadart commented 1 year ago

Thanks. But it is same.

I will show you the changes I made. Here,

Text('Fajr Time: ${DateFormat.jm().format(prayerTimes!.fajr)}'),

@override
  Widget build(BuildContext context) {
    return Center(
      child: Builder(
        builder: (BuildContext context) {
          if (prayerTimes != null) {
            return Column(
              children: [
                const Text('Prayer Times for Today',
                    textAlign: TextAlign.center),
                Text('Fajr Time: ${DateFormat.jm().format(prayerTimes!.fajr)}'),
                Text(
                    'Sunrise Time: ${DateFormat.jm().format(prayerTimes!.sunrise)}'),
                Text(
                    'Dhuhr Time: ${DateFormat.jm().format(prayerTimes!.dhuhr)}'),
                Text('Asr Time: ${DateFormat.jm().format(prayerTimes!.asr)}'),
                Text(
                    'Maghrib Time: ${DateFormat.jm().format(prayerTimes!.maghrib)}'),
                Text('Isha Time: ${DateFormat.jm().format(prayerTimes!.isha)}'),
              ],
            );
          }
          if (locationError != null) {
            return Text(locationError);
          }
          return const Text('Waiting for Your Location...');
        },
      ),
    );
  }
}

and the changes sir @iamriajul , you said me to make.

Here,

late PrayerTimes? prayerTimes;

class _PrayerState extends State<PrayerTimings> {
  final location = Location();
  late String location error;
  late PrayerTimes? prayer times;

  @override
  void initState() {
    getLocationData().then((locationData) {
      if (!mounted) {
        return;
      }
      if (locationData != null) {
        setState(() {
          prayerTimes = PrayerTimes(
              Coordinates(locationData.latitude!, locationData.longitude!),
              DateComponents.from(DateTime.now()),
              CalculationMethod.karachi.getParameters());
        });
      } else {
        setState(() {
          locationError = "Couldn't Get Your Location!";
        });
      }
    });

    super.initState();
  }

  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;
      }
    }
shaadart commented 1 year ago

Error

Reload already in progress, ignoring request
Restarted application in 7,154ms.

════════ Exception caught by widgets library ═══════════════════════════════════
The following LateError was thrown building Builder(dirty):
LateInitializationError: Field 'prayerTimes' has not been initialized.

The relevant error-causing widget was
Builder
shaadart commented 1 year ago

@iamriajul I would love to Seek ur help

iamriajul commented 1 year ago

remove the late keyword from the prayerTimes property.

like so:

class _PrayerState extends State<PrayerTimings> {
  final location = Location();
  String location error;
  PrayerTimes? prayerTimes;

I would suggest taking the Dart Programming Language course before diving into Flutter.

shaadart commented 1 year ago

Alhamdulillah May THe Eternal, All-forgiving, Oft-Forgiver, The Most Greatest, The Highest, Protect you and provide you with the best and build a beautiful home next to the holy prophet saw.

I thank you for your generous help and generous affection, I am new to flutter and you helped me. I pray for you and your family member's health and may there be ease in your and theirs life with barakah. Thanks a lot.

@iamriajul