提问人:UnityBoy 提问时间:5/11/2023 更新时间:5/13/2023 访问量:114
在 null 值上使用的 Null 检查运算符 当我刷新主页或转到主页时
Null check operator used on a null value When I refresh the homepage or go to the homepage
问:
我想我在这里需要帮助。我的代码显示错误“Null Check Operator Used on A null Value”。当我第一次运行/构建应用程序时,一切都很好。apk运行良好。但是,当我单击主页按钮或刷新TextSpan识别器时,会显示空检查警报。您能否看到下面的代码并给我解决此问题的方法。对不起,如果我的英语不好,我希望你能理解问题所在。请帮助:)
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());
});
}
}
我试图用“!”进行checknull,但警报仍然显示。当我去或刷新主路线时,就会发生这种情况。
答:
0赞
Ivo
5/11/2023
#1
这条线很可能会出错
List<MyLocation.Placemark> placemarks = await MyLocation.placemarkFromCoordinates(pLat!, pLong!);
你的代码会到达那里,即使 和 是 .当为 null 时会发生这种情况。我相信你真的想在发生这种情况时退出函数,所以你需要在这样的结尾返回:pLat
pLong
null
locationData
else
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
}
没有它,你的代码就会在它下面继续。
评论
0赞
UnityBoy
5/12/2023
谢谢先生的想法,但我认为这个空问题是因为当我转到另一个页面并返回主页时,回历包没有数据。当我擦除回历变量时,错误消失了。我是颤动的新手。我希望你能理解我并帮助我,先生。
0赞
UnityBoy
5/12/2023
#2
我清楚地知道问题所在。解决方案是我将 var hijri 放在 Widget Build 下面,如下所示:
@override
Widget build(BuildContext context) {
HijriCalendar.setLocal('en');
var _hijrCalendar = HijriCalendar.now();
非常感谢所有试图帮助我的人。
评论