so im calling an API with some JSON feedback like so :
[{"student_name" : "Raskal", "student_classes" : "XII"}]
I call this using this format :
Future< StudentInfo > _studentCard() async {
var data = await MainApi("meKTA", 'getEKTA', '', "getEKTA");
var jsonData = json.decode(data);
var jsonParse = jsonData[0];
final StudentInfo studentinfo = StudentInfo(
jsonParse['student_name'],
jsonParse['student_classes'],
);
print(data);
return studentinfo;
}
class StudentInfo {
final String student_name;
final String student_classes;
StudentInfo(
this. student_name,
this. student_classes,
);
}
I tried to call the API feedback like this
Text(snapshot.data.student_name)
but i get an error on the student_name
the result i want is that the TEXT shows Raskal
Error I got
The property 'student_name' can't be unconditionally accessed because the receiver can be 'null'.
on SDK : ">=2.11.0 <3.0.0", Ive got no problem on calling like that, but on sdk: ">=2.12.0 <3.0.0" ive got that problem
Since SDK 2.12. Flutter using Sound null safety. You have to migrate all of your code to run your app correctly. See more: Sound null safety
Try to check null before passing data into Text.
The simplest way you can do it like this one:
Text(snapshot.data?.student_name ? '')
Related
I'm working with flutter and woocommerce_api: ^0.1.0 .
I'm trying to get all the products in a category that have stock_status=instock but that parameter doesn't work.
The same api consumed from PHP does work, so something in flutter is wrong. I've tried all the ways but I can't get it to work.
If I add the parameter ?category=113 , it does work so some parameters are accepted, but if I add the stock_status not working.
I have hidden the keys for security reasons
Any help?
Future getProduct(int idCategory) async {
WooCommerceAPI wooCommerceAPI = WooCommerceAPI(
url: "x",
consumerKey: "x",
consumerSecret: "x");
var productos = await wooCommerceAPI
.getAsync("products?stock_status='instock'&per_page=100");
return productos;
}
Try without quotes.
var productos = await wooCommerceAPI.getAsync("products?stock_status=instock&per_page=100");
sorry I am new in using Flutter and using Hive local storage.
I am using
hive: ^2.0.4
hive_flutter: ^1.0.0
I open the box in main function like this
Future<void> main() async {
await Hive.initFlutter();
await Hive.openBox<List<Event>>("events");
}
after getting the data from the server, I save all the events to hive by using code like this
final eventsBox = Hive.box<List<Event>>("events");
final List<Event> eventsFromServer = await getEventsFromServer();
eventsBox.put("recommended_events", eventsFromServer);
but I have error when trying to read the data from the box, I read it like this
final eventsBox = Hive.box<List<Event>>("events");
// error in this one line below
final eventsFromHive = eventsBox.get("recommended_events", defaultValue: []) ?? [];
type 'List < dynamic > ' is not a subtype of type 'List< Event >?' in type
cast
how to solve this type casting error?
from the documentation in here it is said
Lists returned by get() are always of type List (Maps of type
Map<dynamic, dynamic>). Use list.cast() to cast them to a
specific type.
I don't know if it is the solution of my problem or not, but I don't know how to implement that in my code.
I tried it like this, but I still have the same error
final eventsFromHive = eventsBox.get("recommended_events")!.cast<Event>();
or maybe the way I write the syntax to save and read the list are totally wrong? please help :)
Is not necessary to open your box as a List, because it is a box and can store many objects of the type that you declare, for example:
await Hive.openBox<MyModel>(boxName);
To get all the objects or data stored in that box, you can query like this:
final box = Hive.box<CompanyModel>(boxName);
List<CompanyModel> interviews = box.values.toList();
In addition, you have to create an Adapter Model if you want to store your own Model with Hive.
There is two dev dependencies to auto generate the Model:
dev_dependencies:
hive_generator:
build_runner:
Importing that dependencies and running this command flutter packages pub run build_runner build will generate the Model, but also you have to create your Model as the documentation indicates.
I suggest you to check out the documentation.
Hive - Generate Adapter
I can finally solve it by using it like this. in main function
Future<void> main() async {
await Hive.initFlutter();
await Hive.openBox("events");
}
when saving data list
final eventsBox = Hive.box("events");
eventsBox.put("recommended_events", eventsFromServer);
and read it like this
final eventsBox = Hive.box("events");
final eventsFromHive = eventsBox.get("recommended_events")?.cast<Event>() ?? [];
I have faced this kind of problem. It was absolutely the same. I do not know how you got kinda problem. Maybe it was the same with mine. I have just cleaned the box. and it has worked on me.
**Cause: **
I started it immediately after I made the box (for testing). he had taken the List<dynamic> object as it store. Once I made it clear, it stocked up data I had just given and it worked
Try:
boxName.clear() inside initState() and re-run it. if it will work do not forget to delete the line!
if you forget, it will clear the box every time.
Done with getting Hive as an List Object :)
Future<List<CustomModel>> getModels() async {
//box = await Hive.openBox<CustomModel>(Constants.Hive);
return box?.values.toList(growable: false)?.cast<CustomModel>() ?? <CustomModel>[];
}
I'm trying to fetch all json data which https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail api returns, to use it in my flutter app
var api="https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail";
var res=await http.get(api);
drinks= jsonDecode(res.body)["drinks"];
but it gives red underline under api parameter in http.get(api) function call that "argument of type string cannot be converted to URI"
How to Resolve this? I even tried using
res=await http.get(Uri.https('www.thecocktaildb.com','/api/json/v1/1/filter.php?c=Cocktail'));
but got error "Error connecting to the service protocol: failed to connect to http://127.0.0.1:63573"/_fprblq_tiY=/"
Instead of using Uri.https(), try using Uri.parse()
Add :
http: ^0.13.4 to your pubspec.yaml , it will provide you with some simple methods to access apis.
You cannot add ? directly because it will convert to 3%F I believe, same for other special characters.
var url = 'thecocktaildb.com';
var urlExtension = '/api/json/v1/1/filter.php';
final Map<String, String> queryParameters = <String, String>{
'c': 'Cocktail',
};
final api = Uri.https(url, urlExtension, queryParameters);
//It should be something like this, now you can get
//the api response the way you were doing:
var res=await http.get(api);
drinks= jsonDecode(res.body)["drinks"];
I was using parse server sdk in my app for database.
I have three class in my Back4App Dashboard which are "_User", "Office", "Office_Members".
In Office_Members class it has following columns,
user_id (Pointer to _User)
office_id (Pointer to Office)
count
To fetch the data including Pointer to _User as well from Office_Members, I am using following code,
QueryBuilder<ParseObject> parseQuery = QueryBuilder<ParseObject>(ParseObject("Office_Members"))
..whereEqualTo("office_id", ParseResponse_OfficeObject)
..includeObject(["user_id "]);
ParseResponse apiResponse = await parseQuery.query();
Output :
Payload : [{"className":"Office_Members","objectId":"twpDY51PUK","createdAt":"2020-08-14T09:58:59.775Z","updatedAt":"2020-08-14T09:58:59.775Z","office_id":{"__type":"Pointer","className":"Office","objectId":"4dkfSMrwBI"},"user_id":{"__type":"Pointer","className":"_User","objectId":"Hx5xJ5ABxG"},"count":1}]
In my payload response i am not getting whole user_id pointer response.
So can anybody help me that what i might be doing wrong?
Thanks.
The data should be included.
The logging function simply does not print the data of pointers.
The data should be included. The print function not print the data of pointers.
You can print it out directly for testing purposes, E.g.
response.results[0].get('user_id').get('name')
Evaluation Expression E.g.
In your model u can access at same way, E.g
Call Model
if(response.success){
return response.results.map((p) => Example.fromParse(p)).toList();
} else {
throw ParseErrors.getDescription(response.error.code);
}
Model
import 'package:parse_server_sdk/parse_server_sdk.dart';
class Example {
Example({this.id, this.name});
Example.fromParse(ParseObject parseObject) :
id = parseObject.objectId,
name = parseObject.get('user_id').get('name');
final String id;
final String name ;
#override
String toString() {
return 'Example{id: $id, name: $name}';
}
}
Why not simply use cloud code ? I'm not to familiar with flutter but I can suggest you this alternative solution.
Write a function like this.
Parse.Cloud.define("fetchMemberAndUser", async (request) => {
//Pass in ParseResponse_OfficeObject ID as parameter
var objectId = request.params.id;
//Now do a simple get query
var query = new Parse.Query(Parse.Object.extend("Office_Members"));
//Using .includes to get the user profile object
query.include("user_id");
//This will return Office_Memebers Object along with user profile
return query.get(objectId,{useMasterKey:true});
}
I am programming a flutter app, in which I have a callback from the native system containing some nfc information. I register the callback via the following line of code:
eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
The callback looks like this:
void _onEvent(Object event) {
//Receive Event
print("NFC Event received");
//Get the Payload
event['Payload']; //This does not work, it gives an error
}
But how can I parse out the data? I know it contains a field by the name Payload however, I cannot access it via event['Payload'].
I am very confused, I tried to cast it to another type like this: Map<String, String> eventMap = Map<String, String>.from(event); but that didnt work. Could someone please point out what I am doing wrong and how I can correctly extract the data?
Without too much information of native part, I suggest
you can reference this package or fork this https://github.com/akeblom/flutter-nfc-reader
directly
this repo fix some issue of pub.dev and work well in real device
the dart code you need reside in
https://github.com/akeblom/flutter-nfc-reader/blob/master/lib/flutter_nfc_reader.dart
void _onEvent(dynamic data) {
print("Event");
print(data);
}
Edit add more detail
akeblom has add Write NFC capability to IOS, so IOS part should work. please ue this fork https://github.com/akeblom/flutter-nfc-reader
For IOS MissingPluginException issue, I do not have IOS, I suggest you can ask akeblom
The data part you mentioned in comments if I do not misunderstand is line 77, please see describe below
In Android part.
https://github.com/akeblom/flutter-nfc-reader/blob/master/android/src/main/kotlin/it/matteocrippa/flutternfcreader/FlutterNfcReaderPlugin.kt
line 174, use kotlin mapOf returns a new read-only map with the specified contents and eventSink.success result to Dart
if (message != null) {
val data = mapOf(kId to id, kContent to message, kError to "", kStatus to "read")
eventSink?.success(data)
}
In https://github.com/akeblom/flutter-nfc-reader/blob/master/lib/flutter_nfc_reader.dart
line 22, with named constructor
factory NfcData.fromMap(Map data) {
NfcData result = NfcData(
id: data['nfcId'],
content: data['nfcContent'],
error: data['nfcError'],
statusMapper: data['nfcStatus'],
);
In line 77, NFC read start and _onEvent(dynamic data) get the data.
stream use this named constructor, and parse data, here with map((result)) transfer to NfcData
static Stream<NfcData> get read {
final resultStream = _channel
.invokeMethod('NfcRead')
.asStream()
.asyncExpand((_) => stream
.receiveBroadcastStream()
.map((result) => NfcData.fromMap(result)));
return resultStream;
In https://github.com/akeblom/flutter-nfc-reader/blob/master/example/lib/main.dart
line 33, response has transfered to NfCData, so example just use _nfcData = response;
FlutterNfcReader.read.listen((response) {
setState(() {
_nfcData = response;
});
});
The simplest way I found to parse an event to a Map is the following:
I encoded the variable to a String (but I use json.encode(event)instead of event.toString()as encode(event)returns a valid string.
Then I use this string to construct a map via json.decode. All of this is achieved with the flutter native library dart:convert. The complete code looks like this:
import 'dart:convert';
...
void _onEvent(dynamic event) {
//Receive Event
print("NFC Event received");
String str = json.encode(event);
Map eventMap = json.decode(str);
}
Have you tried event.toString()? It might return a string containing the field you are trying to get, from which you can easily parse the value.
You may also want to try:
Class<?> clazz = event.getClass();
Field payload= clazz.getField("Payload"); //Note, this can throw an exception if the field doesn't exist.
String fieldValue = payload.toString();
If it isn't returning what you want, you may need to make an interface for the object type, with a get method, or override the toString method to get return the Payload value.