How can i fetch json data without key in Flutter? - flutter

How can i fetch JSON data without key in flutter?
I don't need to create a map to fetch it, i have an url to call it and the json is composed of one single int value. How can i fetch it?

var client = http.Client();
String url = "url";
Response response = await client.get(url);
print('Response status: ${response.statusCode}');
print('Response body: ${json.decode((response.body))}');

There is package called http that can help you to fetch data from your API
so this how you proceed
import http package
import 'package:http/http.dart';
then send request to your API by
Response response = await get(url); this is a asynchronous methosd so make sure to add async in your function
So, as you asked you don't want to create Map variable
this is how you access it
int x = jsonDecode(response.body)['the key']
make sure you import import 'dart:convert'; as it a dependency
if you still have issues comment down below.
Regards,
Roshan

Related

How to connect a flutter mobile app to a rest API in node js which is hosted in heroku?

I have deployed a rest API (nodejs) in Heroku but i want to know how to connect my flutter mobile app with these endpoints.I have looked for solution but i haven't seen anything regarding this.my flutter app is running in my mobile device.Hope any one can give a good solution.
import 'package:http/http.dart' as http;
First import http package do mention that in pubspec,yaml
then
Import convert package if you want to deal with jsondata
import 'dart:convert';
Now you will be creating future functions
for get request:
Future<void> getGoodRequest1() async{
var url = 'your url';
http.Response response = await http.get(url);
String data = response.body;
print(jsonDecode(data));
}
for post request
Future<void> postGoodRequest2() async{
String url = 'your url';
Map<String, String> headers = {"Content-type": "application/json"};
// if you want to pass json along with it
String json = '{"query": "example", "data": "example"}';
// make POST request
http.Response response = await http.post(url, headers: headers, body: json);
// check the status code for the result
print('posted');
}
For more you can refer here Http flutter

RedirectException: Redirect loop detected

I'm testing a request to get data from an URL using dio in my Dart code.
import 'package:dio/dio.dart';
class Api {
Dio dio = Dio();
var path = 'https://jsonplaceholder.typicode.com/users';
void getHttp() async {
try {
Response response = await dio.get(path);
print(response.data);
} catch (e) {
print(e);
}
}
}
In this case it brings the result correctly.
But, I actually need get data from this URL:
http://loterias.caixa.gov.br/wps/portal/loterias/landing/megasena/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbwMPI0sDBxNXAOMwrzCjA0sjIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wNnUwNHfxcnSwBgIDUyhCvA5EawAjxsKckMjDDI9FQE-F4ca/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0KO6H80AU71KG7J0072/res/id=buscaResultado/c=cacheLevelPage/=/?timestampAjax=1588600763910
Using Postman I can access the data:
So, the problem is that, if I try to get data from that URL in my code, I get the following exception error:
I/flutter (23393): DioError [DioErrorType.DEFAULT]: RedirectException: Redirect loop detected
If this URL is redirecting, why is it working when using Postman? Anyway, how could I handle this redirected request in order to access data?
After a while, I noticed that the response to this request is coming as HTML and not as Json. So I needed to create a way to get DOM coming from the request, removing HTML tags and encoding string to Json.

Is there any helper function or Package that helps in Twilio Sms flutter application

I am trying to create a flutter application that sends SMS to relatives of an elderly person if he has not consumed his medicine on time. I was planning on using Twilio but there is not enough documentation and resources for me to implement it. Please help
Have you checked out this Dart helper library for Twilio?
Add a dependency to twilio_dart to your pubspec.yaml
Run pub get
Get a key and authentication code from your Twilio console. The account is limited but free.
Now you can make a new Twilio object with your account details like so:
import 'package:twilio_dart/twilio.dart';
var key = "your_twilio_key";
var authToken = "your_auth_token";
var version = "2010-04-01";
//create a new twilio object
Twilio twilio = new Twilio(key, authToken, version);
To send a SMS with this, add
var from = "your_twilio_phone";
var to = "your_mobile_number";
var body = "Look ma! Dart can now send SMS's in under 15 lines";
and check out the repo for more!
I found another way to do this using just the Http package
import 'package:http/http.dart' as http;
import 'dart:convert';
void sendSMS() async {
var cred =
'ACCOUNT_SID:AUTH_TOKEN';
var bytes = utf8.encode(cred);
var base64Str = base64.encode(bytes);
var url =
'https://api.twilio.com/2010-04-01/Accounts/ACCOUNT_SID/Messages.json';
var response = await http.post(url, headers: {
'Authorization': 'Basic ${base64Str}'
}, body: {
'From': '+xxxxxxxx', //twilio number
'To': '+15558675310',
'Body': 'Hello world!'
});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
Using this function we can send SMS from a Twilio Number. Correct me if I'm wrong. Cheers.

how to get html data from 1 website for about json file in flutter

280/5000
I'm writing an app that read "Yesterday's" story with flutter. How to get data from the website "https://mylifengayhomqua.blogspot.com/2012/04/ngay-hom-qua-tung-chap-1.html". Specifically, get a list of chapters, chapter names, chapter contents for a listview.
First, you have to download the HTML code which you want to parse. You can do it by adding to your code a function like this:
import 'dart:convert';
import 'package:http/http.dart';
import 'package:html/parser.dart';
import 'package:html/dom.dart';
...
Future initiate() async {
var client = Client();
Response response = await client.get(
'https://mylifengayhomqua.blogspot.com/2012/04/ngay-hom-qua-tung-chap-1.html'
);
print(response.body);
return response.body;
}
There's a nice article about scraping HTML, you can find it here.
Then you have to find the right HTML selectors and parse the response.body in this way:
var document = parse(response.body);
List<Element> yourContent = document.querySelectorAll('your selector');
Converting to a map should be easy then and is nicely described in an article above.
Good luck <3

Flutter http Maintain PHP session

I'm new to flutter. Basically I'm using code Igniter framework for my web application. I created REST API for my web app, after user login using API all the methods check for the session_id if it exists then it proceeds, and if it doesn't then it gives
{ ['status'] = false, ['message'] = 'unauthorized access' }
I'm creating app with flutter, when i use the http method of flutter it changes session on each request. I mean, it doesn't maintain the session. I think it destroys and creates new connection each time. Here is thr class method which i use for api calls get and post request.
class ApiCall {
static Map data;
static List keys;
static Future<Map> getData(url) async {
http.Response response = await http.get(url);
Map body = JSON.decode(response.body);
data = body;
return body;
}
static Future postData(url, data) async {
Map result;
http.Response response = await http.post(url, body: data).then((response) {
result = JSON.decode(response.body);
}).catchError((error) => print(error.toString()));
data = result;
keys = result.keys.toList();
return result;
}
I want to make API request and then store session_id,
And is it possible to maintain session on the server so i can manage authentication on the web app it self.?
HTTP is a stateless protocol, so servers need some way to identify clients on the second, third and subsequent requests they make to the server. In your case you might authenticate using the first request, so you want the server to remember you on subsequent requests, so that it knows you are already authenticated. A common way to do this is with cookies.
Igniter sends a cookie with the session id. You need to gather this from each response and send it back in the next request. (Servers sometimes change the session id (to reduce things like clickjacking that we don't need to consider yet), so you need to keep extracting the cookie from every response.)
The cookie arrives as an HTTP response header called set-cookie (there may be more than one, though hopefully not for simplicity). To send the cookie back you add a HTTP request header to your subsequent requests called cookie, copying across some of the information you extracted from the set-cookie header.
Hopefully, Igniter only sends one set-cookie header, but for debugging purposes you may find it useful to print them all by using response.headers.forEach((a, b) => print('$a: $b'));. You should find Set-Cookie: somename=abcdef; optional stuff. We need to extract the string up to, but excluding the ;, i.e. somename=abcdef
On the next, and subsequent requests, add a request header to your next request of {'Cookie': 'somename=abcdef'}, by changing your post command to:
http.post(url, body: data, headers:{'Cookie': cookie})
Incidentally, I think you have a mismatch of awaits and thens in your code above. Generally, you don't want statics in classes, if they should be top level functions instead. Instead you could create a cookie aware class like:
class Session {
Map<String, String> headers = {};
Future<Map> get(String url) async {
http.Response response = await http.get(url, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
Future<Map> post(String url, dynamic data) async {
http.Response response = await http.post(url, body: data, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
void updateCookie(http.Response response) {
String rawCookie = response.headers['set-cookie'];
if (rawCookie != null) {
int index = rawCookie.indexOf(';');
headers['cookie'] =
(index == -1) ? rawCookie : rawCookie.substring(0, index);
}
}
}