I'm trying this certain app (world-time app) and constantly getting this error:
Used this HTTP Package for url:
import 'dart:convert';
import 'package:http/http.dart';
import 'package:intl/intl.dart';
class WorldTime {
String location;
String time;
String flag;
String url;
WorldTime({this.location, this.flag, this.url});
Future<void> getTime() async {
try {
Response response =
await get(Uri.https('worldtimeapi.org', 'api/timezone/$url'));
Map data = jsonDecode(response.body);
String datetime = data['datetime'];
String offset = data['utc_offset'].substring(1, 3);
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offset)));
time = DateFormat.jm().format(now);
} catch (e) {
print("Error occured: $e");
time = "Cannot Display Time Due to Error Occured";
}
}
}
imported world time api in this file:
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:world_time_app/services/world_time.dart';
class loading extends StatefulWidget {
#override
_loadingState createState() => _loadingState();
}
class _loadingState extends State<loading> {
void setTime() async {
WorldTime instance =
WorldTime(location: 'Florida', flag: 'img.jpg', url: 'America/Florida');
await instance.getTime();
Navigator.pushReplacementNamed(context, '/home', arguments: {
'location' : instance.location,
'flag': instance.flag,
'time': instance.time,
});
}
#override
void initState() {
super.initState();
setTime();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(50.0),
child: Text('Loading'),
));
}
}
pls help me Im getting error while running the app:
Restarted application in 1,228ms.
I/flutter (24197): Error occured: NoSuchMethodError: The method 'substring' was called on null.
I/flutter (24197): Receiver: null
I/flutter (24197): Tried calling: substring(1, 3)
I/flutter (24197): {location: Florida, flag: img.jpg, time: Cannot Display Time Due to Error Occured}
I think I made DateTime Object thats why it is showing error, is there any alternative to this?
Any help will be much appreciated :)
The error you are getting is most likely because utc_offset is null.
You can check if it's actually null or not, and that it's length is at least 3 before performing substring(1,3) on it, like this:
String offset =
data['utc_offset'] == null || data['utc_offset'].length >= 3
? "utc offset has a problem"
: data['utc_offset'].substring(1, 3);
Related
I have some code to get files from a json file, only I get a message and not know how to solve that, any ideas?:
List<LatLng> polylineCoordinates = [];
#override
void initState() {
polylineCoordinates = readJson().map((e)=> LatLng(e['lat'], e['long'])).tolist();
super.initState();
}
The error is:
Class 'Future<dynamic>' has no instance method 'map'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: map(Closure: (dynamic) => LatLng)
I just want to get a weather forecast data from the Internet. I wrote this code below but every time I got the error:
A non-null String must be provided to a Text widget
For some reason I could not take decoded json data
import 'package:flutter/material.dart';
import 'network.dart';
class HomePage extends StatefulWidget {
static String id;
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Map<String,dynamic> currentPositionWeatherData;
String temperature;
String weatherDescription;
String name;
void initState(){
super.initState();
getCurrentLocationWeather();
updateUI();
}
void getCurrentLocationWeather()async{
currentPositionWeatherData=await NetworkHelperForWeatherInfo().getCurrentPositionWeatherData();
}
void updateUI()async{
setState(() {
weatherDescription = currentPositionWeatherData["weather"][0]["description"];
temperature = currentPositionWeatherData["main"]["temp"];
name = currentPositionWeatherData["name"];
});
}
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.black,
child: Text(
temperature,
),
),
);
}
}
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart';
const openWeatherURL="http://api.openweathermap.org/data/2.5/weather";
const apikey="57aad03f4e48ca815bb1184e74624f46";
class NetworkHelperForWeatherInfo{
Future getCurrentPositionWeatherData()async{
Position position = await Geolocator.getCurrentPosition();
Response response = await get("$openWeatherURL?lat=${position.latitude}&lon=${position.latitude}&appid=$apikey");
if(response.statusCode ==200){
String currentPositionWeatherData = response.body;
return jsonDecode(currentPositionWeatherData);
}
else{
return response.statusCode;
}
}
}
import 'package:flutter/material.dart';
import 'homepage.dart';
import 'package:geolocator/geolocator.dart';
class LocationFinder{
bool serviceEnabled;
LocationPermission permission;
Future<Position> determineCurrentPosition()async{
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(serviceEnabled != true){
return Future.error("Location services are disabled");
}
permission = await Geolocator.checkPermission();
if (permission==LocationPermission.deniedForever) {
return Future.error("Location permissions are permantly denied,we cannot request permissions.");
}
if (permission == LocationPermission.denied){
permission = await Geolocator.requestPermission();
if(permission != LocationPermission.whileInUse &&
permission != LocationPermission.whileInUse){
return Future.error("Location permission are denied/ actual value:$permission");
}
}
Position position =await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
return position;
}
}
child: Text(
temperature ?? 'waiting data...',
)
When _HomePageState State widget is first built, temperature variable will be null (until data is retrieved and the widget rebuilt through setState call). A null value isn't allowed by the Text widget which asserts the text value not be null.
The above change will supply the text waiting data... when temperature is null.
i was trying out a tutorial on Flutter course (https://www.udemy.com/share/101WB6/) in which location data is retreived from API call and the error shows up while decoding the data,
i tried changing the data types of the variables but still the error persists.
the error message is:
The following _TypeError was thrown building Builder:
type 'String' is not a subtype of type 'int' of 'index'
The relevant error-causing widget was:
MaterialApp file:///C:/Users/saleem/StudioProjects/Clima/lib/main.dart:9:12
When the exception was thrown, this was the stack:
#0 _LocationScreenState.updateUI (package:clima/screens/location_screen.dart:25:30)
#1 _LocationScreenState.initState (package:clima/screens/location_screen.dart:21:5)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4765:58)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
... Normal element mounting (132 frames)
i tried changing the data types of variables to be all String and all var, iam really to the programming scene
i will attach the dart code below:
import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';
class LocationScreen extends StatefulWidget {
LocationScreen({this.locationWeather});
final locationWeather;
#override
_LocationScreenState createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
double temperature;
int condition;
String cityName;
#override
void initState() {
super.initState();
print(widget.locationWeather);
updateUI(widget.locationWeather);
}
void updateUI(dynamic weatherData) {
temperature = weatherData['main']['temp'];
condition = weatherData['weather'][0]['id'];
cityName = weatherData['name'];
}
#override
Widget build(BuildContext context) {
return Scaffold(
...
);
}
}
and here is the API output
I/flutter (14299): "{\"coord\":{\"lon\":139.01,\"lat\":35.02},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}],\"base\":\"stations\",\"main\":{\"temp\":285.514,\"pressure\":1013.75,\"humidity\":100,\"temp_min\":285.514,\"temp_max\":285.514,\"sea_level\":1023.22,\"grnd_level\":1013.75},\"wind\":{\"speed\":5.52,\"deg\":311},\"clouds\":{\"all\":0},\"dt\":1485792967,\"sys\":{\"message\":0.0025,\"country\":\"JP\",\"sunrise\":1485726240,\"sunset\":1485763863},\"id\":1907296,\"name\":\"Tawarano\",\"cod\":200}"
The issue is solved i had used jsonEncode instead of jsonDecode
The API output is a string.
Firstly import 'dart:convert';
And wrap your API output in jsonDecode( API_OUTPUT ).
That'll make it into a json object whose contents can then be accessed in the way that you are doing.
A link to the tutorial would have been nice. I guess it is
condition = weatherData['weather'][0]['id'];
which should be
condition = weatherData['weather']['0']['id'];
int condition => String condition;
or parse line 30 to int
I am new to dart.
I am working with Futures and learning more about types along the way (coming from a python background, so no experience in types). My code has no errors but, kindly explain to me why I can change my function's type from Future<List> when creating it to Function in initState. Here is the code:
Future<List> getData() async {
String ss = await Future.delayed(Duration(seconds: 1),(){
return 'first name';
});
String ssTwo = await Future.delayed(Duration(seconds: 1), (){
return 'last name here.';
});
List lista = [ss, ssTwo];
return lista;
}
#override
void initState() {
Function getit = getData; // Why if I set it to Future<List> in here I get an exceptio?
print('placeholder');
super.initState();
}
Why in initState if I set the type to Future<List> I get this exception?
A value of type 'Future<List<dynamic>> Function()' can't be assigned to a variable of type 'Future<List<dynamic>>'.
Try changing the type of the variable, or casting the right-hand type to 'Future<List<dynamic>>'.
The getData() return Future<List> while you tring to assign Future<List> in to a Function() that's why you are getting error
Try this way to get Future<List> from getData() method
#override
void initState() {
super.initState();
getData().then((list) =>
{
list.forEach((element) {
debugPrint('LIST_ITEM $element');
})
});
print('placeholder');
}
OUTPUT
I'm new to flutter and learning through a tutorial about Flutter So I was following the same codes and already tried rewriting almost everything but when I started to run the app and i got that above error.
ERROR:flutter/lib/ui/ui_dart_state.cc(157)
Exception: FormatException: Unexpected character (at character 1)
E/flutter (14218):
My codes:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
class Loading extends StatefulWidget {
#override
_LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void getTime() async {
Response response= await get('http://worldtimeapi.org/timezone/Europe/London');
Map data=jsonDecode(response.body);
print(data);
}
#override
void initState() {
// TODO: implement initState
super.initState();
getTime();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(
backgroundColor: Colors.blue[800],
title: Text('here is loading'),
),
body: Text("choose location screen"),
);
}
}
I think you mean this link: https://worldtimeapi.org/api/timezone/Europe/London.
Not this one:
Response response= await get('http://worldtimeapi.org/timezone/Europe/London');
The link I gave you above gives you a JSON response in which you decode in your app. You were linking to an actual webpage that doesn't give you a JSON response, that's why you got that error. I have also made it HTTPS so it's more secure in your app.