Class 'Future<dynamic>' has no instance method '[]' - android

enter image description hereFuture dynamic not working please help trying to make a weather app
class WeatherModel {
Future<dynamic> getLocationWeather() async{
Location location = Location();
await location.getCurrentLocation();
Networkhelper networkhelper = Networkhelper(
'$openWeatherMapURL
lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');
var weatherData = await networkhelper.getData();
return weatherData;
}}

your code should look like this:
Confirm your URL matches mine. Seems like you're missing ?.
Future<dynamic> getLocationWeather() async {
Location location = Location();
await location.getCurrentLocation();
NetworkHelper networkHelper = NetworkHelper(
url: // if you used a positional argument.
'$openWeatherMapURL?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');
var weatherData = await networkHelper.getData();
return weatherData;
}

Related

2 Problems from Flutter Beginner Course from Angela, Clima project after refactoring code

1) From loading_screen.dart :
Error : Instance member 'getData' can't be accessed using static access.
Locator( ) is my location handling class.
import 'package:flutter/material.dart';
import 'package:clima/services/location_handler.dart';
import 'package:clima/services/networking.dart';
const myAPI = 'cant post api online but its just alphabets and numbers passed as a string';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
late double latitood;
late double longitood;
void initState() {
//this method is called the moment we run our app.
super.initState();
getLocationData();
}
void getLocationData() async {
Locator loca = Locator();
await loca.getCurrentLocation();
latitood = loca.latitude;
longitood = loca.longitude;
NetworkHelper NetHelp = NetworkHelper(
//pasing url info into Network Helper class.
'https://api.openweathermap.org/data/2.5.weather?lat=$latitood&lon=$longitood&appid=$myAPI');
var weatherDataFinal = await NetworkHelper.getData();
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
2) From networking.dart :
Error : The argument type 'String' can't be assigned to the parameter type 'Uri'.
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(url);
//passing url as a single string to get method to get Response.
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
//decoding and putting data into decodedData variable of dynamic type.
return decodedData;
} else {
print(response.statusCode);
}
}
}
Did someone encounter these problems ? If you did and found a Solution then please help me !!!!
This await NetworkHelper.getData(); should be await NetHelp.getData(); because that is how you named your variable.
await http.get(url); should be await http.get(Uri.parse(url));

Can't get Future Value from DIO Flutter

I'm really new in Flutter programming. I've problem while try to get value from Future. After I get it, I want to deserialize it for further processing.
The return value from the Future is on JSON Array.
What should I do to solve this situation?
class _MyAppState extends State<BodyWidget>
{
bool loading = true;
List<Widget> listArray = [];
Dio dio = new Dio();
dynamic isicontent = null;
Future<dynamic> getOrderHistory() async {
final String pathUrl = "http://p.q.r.s/mobile/QIXGetShipmentHistory/" + await FlutterSession().get("MobileUsername");
var responseDio = await dio.get(pathUrl, options: Options( headers: {'Content-Type': 'application/json; charset=UTF-8' } ) );
print(responseDio.data); // It's works fine here...
return responseDio.data;
}
void renderIconShipmentOrderHistory()
{
var resultRespon = getOrderHistory();
print(resultRespon); //the problem is here...
}
}
The return statement needs to return a Future; something alike:
return dio.get(
pathUrl,
options: Options(
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
)
)
The async keyword from the signature likely can be removed, as there is no more await.
Obviously, not returning a Future but awaiting the result may be the other option.

Flutter “this function has a return type of void and I want a return type of map”

I am getting this error:This expression has a type of 'void' so its value can't be used.
Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.
code:
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_hot/angel_hot.dart';
import 'package:logging/logging.dart';
import 'dart:async';
import 'package:mongo_dart/mongo_dart.dart';
main() async {
var hot = HotReloader(createServer, ['main.dart']);
await hot.startServer('127.0.0.1', 3000);
}
Future<Angel> createServer() async {
var app = Angel();
app.logger = Logger('Log')..onRecord.listen((event) => print(event));
print('start server..');
Db db = Db('mongodb://localhost:27017/wearina');
await db.open();
print('connected to ${db.databaseName}');
DbCollection userscoll = DbCollection(db, 'users');
print('${userscoll.collectionName}');
app.post('/signup', (req, res) async {
var body = await req.parseBody(); //// parseBody => Future<void> , I want => Future<Map> ):
var name = body['name'];
var lastname = body['lastname'];
var email = body['email'];
var phone = body['phone'];
var pass = body['pass'];
});
return app;
}
I don't understand what this is. I am new to flutter. This is my first app. Can someone please help me with this.
It seems that parseBody does not return a map of the pasred body. It just makes sure the body is parsed and you can access it from the req.bodyAsMap property. So your line should be:
await req.parseBody();
var body = req.bodyAsMap;

cant save json.decode to share preferences in flutter

I have list, I want to save in sharepreferences,
setString('key',json.encode(temporaryData));
When I try to get this value, only show Instance of Future<dynamic>
but when i print that json.encode show it value
[{"name":"Stranger","birthDate":"","idCardNum":"-1","currentTime":1593598133479,"imageFlag":1,"imageName":"-1_1_1593598133479.png","type":-1,"tempratrue":"36.3","mask":0}]
Future<SharedPreferences> storage() {
return SharedPreferences.getInstance();
}
void setTempData(String temp) async {
SharedPreferences sharedPreferences = await storage();
await sharedPreferences.setString('datas', temp);
}
getTempData(String key) async {
SharedPreferences sharedPreferences = await storage();
await sharedPreferences.get(key);
}
_getTemp() async {
DateTime start = DateTime.now().subtract(Duration(seconds: 5));
DateTime end = DateTime.now();
Map data = {'pass': '123456', 'startTime': '$start', 'endTime': '$end'};
var response = await http.post('$urlApiQr:8080/newFindRecords', body: data);
var jsonData = json.decode(response.body);
var jsEnc = json.encode(response.body);
TempJson tempJson = TempJson.fromJson(jsonData);
var parse = json.decode(tempJson.config);
setState(() {
dataList = parse;
temporaryData = dataList.toSet().toList();
setTempData(json.encode(temporaryData));
//try to print value
print('$start and $end');
print(parse);
print(getTempData('datas'));
});
}
Is there a solution to my problem?
UPDATE 2.0
you have to add await anywhere your are requesting value from a Future.. as the below method return a Future as you can see from your error, just add await keyword from where you are requesting a value,
for example
print(await getTempData(key));
UPDATE
return keyword missing
getTempData(String key) async {
SharedPreferences sharedPreferences = await storage();
//you missed the return keyword here
return await sharedPreferences.get(key);
}
original answer
dont miss the await keyword
var thestring = await sp.getString('the_key');
var theJsonObj = json.decode(thestring);
this is my assumption, please post more code

Flutter Firebase - Get a specific field from document

I'm trying to get a specific field called "specie" from a document in a Firebase collection. I am trying as follows but I have an error of type 'Future ' is not a subtype of type 'String'. What am I doing wrong?
Repository method:
getSpecie(String petId) {
Future<DocumentSnapshot> snapshot = petCollection.document(petId).get();
return snapshot.then((value) => Pet.fromSnapshot(value).specie);
}
Entity method:
factory Pet.fromSnapshot(DocumentSnapshot snapshot) {
Pet newPet = Pet.fromJson(snapshot.data);
newPet.reference = snapshot.reference;
return newPet;
}
factory Pet.fromJson(Map<String, dynamic> json) => _PetFromJson(json);
Pet _PetFromJson(Map<String, dynamic> json) {
return Pet(json['name'] as String,
specie: json['specie'] as String);
}
I found a solution. No needed fromJson() method, I only changed the repository method:
Future<String> getSpecie(String petId) async {
DocumentReference documentReference = petCollection.document(petId);
String specie;
await documentReference.get().then((snapshot) {
specie = snapshot.data['specie'].toString();
});
return specie;
}
Try this..
getSpecie(String petId) async{
Future<DocumentSnapshot> snapshot = await petCollection.document(petId).get();
return snapshot.then((value) => Pet.fromSnapshot(value).specie);
}
This is how I learned to get documents from firestore
https://medium.com/#yasassandeepa007/how-to-get-sub-collection-data-from-firebase-with-flutter-fe1bda8456ca

Categories

Resources