trying to display an alert or warning as a way of catching an error when weatherData is set to null. but when I test it or try to turn of location the spinkit just keeps loading and does not move to the location_screen to display the alert message. I used a condition under updateUI to display the message when weatherData == null.
import 'package:clima_app/services/weather.dart';
import 'package:flutter/material.dart';
import 'package:quickalert/models/quickalert_type.dart';
import 'package:quickalert/widgets/quickalert_dialog.dart';
import '../utilities/constants.dart';
class LocationScreen extends StatefulWidget {
const LocationScreen({super.key, this.locationWeather});
final dynamic locationWeather;
@override
State<LocationScreen> createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
WeatherModel weather = WeatherModel();
late int temperature;
late String weatherIcon;
late String cityName;
late String weatherMessage;
@override
void initState() {
super.initState();
updateUI(widget.locationWeather);
}
void updateUI(dynamic weatherData) {
setState(() {
//This is the condition for showing the alert message
if (weatherData == null) {
QuickAlert.show(
context: context,
type: QuickAlertType.error,
title: 'Error',
text: 'Oops! Something went wrong.',
textColor: Colors.red,
);
return;
}
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id'];
weatherIcon = weather.getWeatherIcon(condition);
weatherMessage = weather.getMessage(temperature);
cityName = weatherData['name'];
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: const AssetImage('images/location_background.jpg'),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(Colors.white.withOpacity(0.8), BlendMode.dstATop),
),
),
constraints: const BoxConstraints.expand(),
child: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
OutlinedButton(
onPressed: () async {
var weatherData = await weather.getLocationWeather();
updateUI(weatherData);
},
child: const Icon(
Icons.near_me,
size: 50.0,
),
),
OutlinedButton(
onPressed: () {},
child: const Icon(
Icons.location_city,
size: 50.0,
),
),
],
),
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Row(
children: <Widget>[
Text(
'$temperature°',
style: kTempTextStyle,
),
Text(
weatherIcon,
style: kConditionTextStyle,
),
],
),
),
Padding(
padding: const EdgeInsets.only(right: 15.0),
child: Text(
"$weatherMessage in $cityName",
textAlign: TextAlign.right,
style: kMessageTextStyle,
),
),
],
),
),
),
);
}
}
This is the first screen from which the location screen is pushed...
import 'package:clima_app/screens/location_screen.dart';
import 'package:clima_app/services/weather.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
const LoadingScreen({super.key});
@override
State<LoadingScreen> createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
@override
void initState() {
super.initState();
getLocationData();
}
void getLocationData() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
//END OF TEST... END OF TEST... END OF TEST... END OF TEST... END OF TEST... END OF TEST
var weatherData = await WeatherModel().getLocationWeather();
Navigator.push(context, MaterialPageRoute(builder: (context) {
return LocationScreen(
locationWeather: weatherData,
);
}));
}
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: SpinKitWave(
size: 50.0,
color: Colors.blueAccent,
),
),
);
}
}
This is location.dart which has the geolocater package where I placed the try and catch error:
import 'package:geolocator/geolocator.dart';
class Location {
late double latitude;
late double longitude;
Future<void> getCurrentLocation() async {
try {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
latitude = position.latitude;
longitude = position.longitude;
} catch (e) {
print(e);
}
}
}
And this is the network.dart which has the http.get response
import 'dart:convert';
import 'package:http/http.dart' as http;
class NetworkHelper {
NetworkHelper(this.url);
final String url;
Future getData() async {
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
String data = response.body;
return jsonDecode(data);
} else {
print(response.statusCode);
}
}
}
CodePudding user response:
change updateUI
to this:
void updateUI(dynamic weatherData) {
if (weatherData == null) {
QuickAlert.show(
context: context,
type: QuickAlertType.error,
title: 'Error',
text: 'Oops! Something went wrong.',
textColor: Colors.red,
);
}else {
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id'];
weatherIcon = weather.getWeatherIcon(condition);
weatherMessage = weather.getMessage(temperature);
cityName = weatherData['name'];
setState(() {});
}
}
CodePudding user response:
try this, please fix comma and semi-col-
void updateUI(dynamic weatherData, BuildContext context) {
if (weatherData == null) {
showDialog(context: context, builder: ((context) => AlertDialog(titleTextStyle: "Oops! Something went wrong.", actions: [
TextButton(onPressed: () => Navigator.of(context).pop(), child: Text('Okhy'))
],)))
}else {
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id'];
weatherIcon = weather.getWeatherIcon(condition);
weatherMessage = weather.getMessage(temperature);
cityName = weatherData['name'];
setState(() {});
}
}