Необработанное исключение: Ошибка LateInitializationError: Поле «isDayTime» не было инициализировано

#flutter #dart

Вопрос:

 [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: LateInitializationError: Field 'isDayTime' has not been initialized.
E/flutter ( 5534): #0      WorldTime.isDayTime (package:world_time/services/world_time.dart)
E/flutter ( 5534): #1      _ChooseLocationState.updateTime (package:world_time/pages/choose_location.dart:34:28)
E/flutter ( 5534): <asynchronous suspension>
 

класс мирового времени

  import 'package:http/http.dart';
  import 'dart:convert';
   import 'package:intl/intl.dart';

class WorldTime {
  late String location;
  late String time;
  late String flag;
  late String url;
  late bool isDayTime;

  WorldTime({required this.location, required this.flag, required this.url});

  Future<void> getTime() async
  {
    try {
      // make request
      Response response = await get(
          Uri.parse('http://worldtimeapi.org/api/timezone/$url'));
      //print(response.body);
      Map data = jsonDecode(response.body);
      //print(data);

      //get properties from data
      String datetime = data['datetime'];
      String offset = data['utc_offset'].substring(1, 3);

      // create date time abject
      DateTime now = DateTime.parse(datetime);
      now = now.add(Duration(hours: int.parse(offset)));
      //set the time property
      isDayTime = now.hour > 6 amp;amp; now.hour < 19 ? true : false;
      time = DateFormat.jm().format(now);
    }
    catch (e) {
      print('some ERROR was found!! $e');
      time = 'Could not Load Time Now';
    }
  }
}
 

страница выбора местоположения

 import 'package:flutter/material.dart';
import 'package:world_time/services/world_time.dart';

class ChooseLocation extends StatefulWidget {
  @override
  _ChooseLocationState createState() => _ChooseLocationState();

}

class _ChooseLocationState extends State<ChooseLocation> {


List<WorldTime> locations = [
    WorldTime(url: 'Europe/London', location: 'London', flag: 'uk.png'),
    WorldTime(url: 'Europe/Berlin', location: 'Berlin', flag: 'greece.png'),
    WorldTime(url: 'Africa/Cairo', location: 'Cairo', flag: 'egypt.png'),
    WorldTime(url: 'Africa/Nairobi', location: 'Nairobi', flag: 'kenya.png'),
    WorldTime(url: 'Africa/Mogadishu', location: 'Mogadishu', flag: 'somalia.png'),
    WorldTime(url: 'Africa/Lagos', location: 'Lagos', flag: 'nigeria-flag-std.jpg'),
    WorldTime(url: 'Africa/Johannesburg', location: 'Johannesburg', flag: 'south.jpg'),
    WorldTime(url: 'America/Chicago', location: 'Chicago', flag: 'usa.png'),
    WorldTime(url: 'America/New_York', location: 'New York', flag: 'usa.png'),
    WorldTime(url: 'Asia/Seoul', location: 'Seoul', flag: 'south_korea.png'),
    WorldTime(url: 'Asia/Jakarta', location: 'Jakarta', flag: 'indonesia.png'),
  ];
  void updateTime(index) async{
    WorldTime instance = locations[index];
    await instance.getTime();
    //navigate to home page
    Navigator.pop(context,{
      'location': instance.location,
      'flag': instance.flag,
      'time':instance.time,
      'isDayTime':instance.isDayTime,
    });
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        backgroundColor: Colors.blue[900],
        title: Text('Choose Location'),
        centerTitle: true,
        elevation: 0,
      ),
      body: ListView.builder(
        itemCount: locations.length,
        itemBuilder: (context,index){
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 4),
            child: Card(
              child: ListTile(
                onTap: (){
                 updateTime(index);
                },
                title: Text(locations[index].location),
                leading: CircleAvatar(
                  backgroundImage: AssetImage('assets/${locations[index].flag}'),
                ),
              ),
            ),
          );
        },
      ),

    );
  }
}
 

Комментарии:

1. Если getTime возникает исключение, вы проглатываете исключение и оставляете isDayTime его неинициализированным. Вы уверены, что этого не происходит?

2. если это так, то каково решение

3. Либо инициализируйте isDayTime этот путь сбоя, либо сделайте его недействительным.