Class 'Future<dynamic>' has no instance method - json

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)

Related

ERROR : NoSuchMethodError: The method 'substring' was called on null

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

type 'String' is not a subtype of type 'int' of 'index' while getting location API from openweathermap

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

Flutter Dart why changing the object type does not result in an error?

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

'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

I need to store my IEnumerable of objects into Tempdata for my next request from the server. Since Tempdata cannot store Objects I found the below extenstion method to serialize and deserialize before putting into Tempdata. After this method, I am able to store my object to Tempdata. But, when I am trying to use it in my next action method, I am facing following runtime error. "Cannot deserialize the current JSON array". Please help me to fix this issue.
my code :
public ActionResult GetData(){
List<EmployeeViewModel> webform =
_service.GetListOfWebformData(id).ToList();
TempData.Put("webform", webform); }
public ActionResult ShowData(){
var WebformData = TempData.Get<EmployeeViewModel>("webform");
return View(WebformData);}
Extension method i have used for Tempdata is below
public static class TempDataExtensions
{
public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
tempData[key] = JsonConvert.SerializeObject(value);
}
public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
object o;
tempData.TryGetValue(key, out o);
return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
}
}

An error (Call to a possibly undefined method echo through a reference with static type) when a calling a class method of an object

I have a structure with PluginMediator class and ServiceProxy class. They both are within the same namespace and when I am creating an object of the proxy class and try to invoke each of its methods I receive the following error:
Call to a possibly undefined method echo through a reference with
static type
Fla code
var _proxy:MyServiceProxy = new MyServiceProxy();
// calls MyService to echo a string and return to onHelloResult.
_proxy.echo("Hi", onHelloResult, null);
_proxy.echo("world!", onHelloResult);
MyServiceProxy class
public class MyServiceProxy extends BaseProxy
{
public function echo(message:String, callback:Function = null, context:Object = null):void
{
callService("echo", [message], callback, context);
}
}
I found the problem. Because I am not quite familiar with services and vsphere(flash) sdk, I renamed the class without the word Mediator. Once I returned the word in the name, everything just went fine. For now;)