convert JSON to array -flutter - json

so im using sql_conn dependency on my flutter project to connect database to my flutter project.
im following the example in the flutter package site and using this method
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
setState(() {
res = req;
});
}
the problem is, res is showing an Stringlike this
[{"CUST_NAME" : "MY NAME"}]
and i just want to show MY NAME later in Text() widget.
How do i parse res so i can get only MY NAME Value

try this, and read more here
import 'dart:convert';
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
var parsedJson = jsonDecode(req);
setState(() {
res = parsedJson[0]['CUST_NAME'];
});
}

Try this once
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
setState(() {
res =req[0]["CUST_NAME"];
});
}
Please try this let me know if it works for you if you need more modification then pls provide me with your print(req) so I can get more ideas and prepare as you want

Related

Use data accross all components

Created a component where I call all my api's. How do I use that data across all my other components
export let resultData = axios
.get(`https://swapi.dev/api/people/1`) //used a dummy api to test
.then(({ data }) => data);
export default class CacheService {
static myInstance = null;
result = resultData;
static getInstance() {
if (CacheService.myInstance == null) {
CacheService.myInstance = new CacheService();
}
return this.myInstance;
}
findAll() {
console.log(this.result);
return this.result;
}
}
You have created a promise and assigned to resultData variable but its not actually resolved.
Either you can use await or use then to get the data.
let testData = await newData.findAll();
or
newData.findAll().then((data)=>{
testData = data;
});
You need to await for the axios to resolve.
async findAll() {
const actualResult = await this.result;
console.log(actualResult);
return actualResult;
}

Can not initialize jsonResponse in Flutter project

In my project I get my json string which later on i tried to assign to it a jsonResponse variable but I got an error like : The argument type 'Response' can't be assigned to the parameter type 'String'.
Here's my code:
Future getMahalle() async {
BaseOptions options = new BaseOptions(
baseUrl: globals.PROD_URL,
connectTimeout: 5000,
receiveTimeout: 3000,
);
Dio dio = new Dio(options);
dio.options.headers["Authorization"] = "Bearer ${globals.USER_TOKEN}";
try {
var response =
await dio.get(globals.SELECT_URL); //'api/hizlirapor/selects'
final jsonResponse = jsonDecode(response); //Here is the error line
MahalleModel mahalleList =
MahalleModel.fromJson(jsonDecode(response.data['mahalle']));
return mahalleList;
} on DioError catch (e) {
debugPrint("ERRORR!!!!!!!!!!!!! ${e.error.toString()}");
return null;
}
}
I'm trying to implement this article for example and got stuck. Thanks for help!
You don't have to decode json returned since you are using dio, dio does that for you.
// if it's a single value than try this.
MahalleModel mahalleList = response.data.map<MahalleModel>((mahalle) => MahalleModel.fromJson(mahalle));
// if it's a list than try this.
List<MahalleModel> mahalleList = response.data['mahalle'].map<MahalleModel>((mahalle) => MahalleModel.fromJson(mahalle)).toList();

Flutter fetch JSON from external Storage

I am trying to read a json file from external Storage (Android). But unable to do it.
I already setup the permission in manifest also checking the permission before reading. Though the file is already in the directory cannot read it.
ModelTestModel modelTestModel;
List<ModelTests> listModelTests;
Future<bool> get readPermission async {
await new Future.delayed(new Duration(seconds: 1));
bool checkResult = await SimplePermissions.checkPermission(
Permission.ReadExternalStorage);
if (!checkResult) {
var status = await SimplePermissions.requestPermission(
Permission.ReadExternalStorage);
if (status == PermissionStatus.authorized) {
var res = await fetchModelTest;
return res != null;
}
} else {
var res = await fetchModelTest;
return res != null;
}
return false;
}
Future<List<ModelTests>> get fetchModelTest async {
var dir = await getExternalStorageDirectory();
print(dir);
final data =
await rootBundle.loadString("${dir.path}/BCS/bsc.json");
print(data);
// var data = await rootBundle.loadString('assets/database/bcs-preparation.json'); this is working when when the file is inside assets
var jsonData = json.decode(data);
modelTestModel = ModelTestModel.fromJson(jsonData);
listModelTests = modelTestModel.modelTests;
return listModelTests;
}
Log
I/SimplePermission(17862): Checking permission :
android.permission.READ_EXTERNAL_STORAGE I/flutter (17862): Directory:
'/storage/emulated/0'
the permission is successful but cannot read the file
rootBundle is used to access the resources of the application, it cannot be used to access the files in phone storage.
Open the file with
File jsonFile = await File("${dir.path}/BCS/bsc.json");
Then decode this jsonFile using
var jsonData = json.decode(jsonFile.readAsStringSync());

Dart Future HttpCLientRequest Returns Null

The class Requests set up an HttpClientRequest. The method getTeamsJsonForRequest is supposed to return the JSON response. However, the variable 'return' is not being assigned properly I assum. The print 'CONTS' in the .then response successfully prints the correct response, but printing 'myres' sections says result is null. Not sure why result is not being assigned in the response.transform section.
class Requests {
static Future getTeamsJsonForRequest(String reqPath) async{
var result;
HttpClient myhttp = new HttpClient();
String path = '/api/v3' + reqPath;
myhttp.get('www.thebluealliance.com', 80, path)
.then((HttpClientRequest request) {
request.headers.set("accept", "application/json");
request.headers.set("X-TBA-Auth-Key", "XXXXX");
return request.close();
})
.then((HttpClientResponse response) {
response.transform(utf8.decoder).transform(json.decoder).listen((conts) {
print('CONTS: ' + conts.toString());
result = json.decode(conts).toString();
});
});
print('myres: ' + result.toString());
return result;
}
}
Short answer: avoid using Future.then inside an async method.
Your print is executing before the response comes back. https://www.dartlang.org/tutorials/language/futures#async-await
Without an await any work that is done asynchronously will happen after subsequent statements in this function are executed.
Here is how I'd write this:
Future<String> teamsJsonForRequest(String requestPath) async {
var client = new HttpClient();
var path = '/api/v3$requestPath';
var request = (await client.get('www.thebluealliance.com', 80, path))
..headers.set("accept", "application/json")
..headers.set("X-TBA-Auth-Key", "XXXXX");
var response = await request.close();
var result =
await response.transform(utf8.decoder).transform(json.decoder).single;
print('myres: $result');
return result;
}

Empty GET response on requesting JSON file's content | koa2

I am a new to koa2, and I trying to GET the contents of a JSON file with koa2
app.use( async ( ctx ) => {
let url = ctx.request.url;
if (url == "list") {
let res = ctx.request.get('http://domain/hello.json');
ctx.body = res.body;
}
})
The JSON file hello.json looks like the following:
{"da": "1212", "dad": "12addsf12"}
I want the route /list to return the contents of hello.json, however, the response is empty. What do I do?
Update:
Change the following lines of code:
let res = ctx.request.get('http://domain/hello.json');
ctx.body = res.body;
to:
let res = ctx.get('http://domain/hello.json');
ctx.body = res;
You should get the content now.
Koa by itself does not support routing, only middleware, you need to have a router middleware for that, try koa-router.
Your app would look something like
const route = require('koa-route')
app.use(route.get('/list', ctx => {
// Route handling logic
});
Also note that ctx.get is an alias for ctx.request.get which returns header information.
This may not be Koa's way of doing things, but this is what I tried and worked for me (complete code for noobs like me):
// jshint ignore: start
const koa2 = require("koa2");
const router = require('koa-simple-router');
const app = new koa2();
const request = require('request-promise-native');
// response
app.use(router(_ => {
_.get('/list', async (ctx) => {
const options = {
method: 'GET',
uri: 'http://www.mocky.io/v2/5af077a1310000540096c672'
}
await request(options, function (error, response, body) {
// I am leaving out error handling on purpose,
// for brevity's sake. You must in your code.
ctx.body = body;
})
});
}));
app.listen(3000);
And, like what J Pichardo's answer points out, Koa by itself does not support routing. You need to use some routing middleware.