i'm trying to fetch data from a range of two columns on google sheet
first column with numbers,second column text
to my flutter app.
i managed to make the the http request
by this line of code:
var url = Uri.parse(
'https:`enter code here`//script.googleusercontent.com/macros/echo?user_content_key=Bzv-qcg70rUkHCr4pjI_k_qlB9c5I_GjKS-U726WCslGZ0tulYSbfdD1DabRoVrrbDSn9rIS78vQxr33OOOjaAw4d4DcA8sGm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnBqJjZp2jp3I5Qlxq6dcbGTdqr4FTByb3YAAvkZxH-A03NfLQ3Ce8hucRs86AXu4Vcg63MBXANpH4BVmytCxmg24Mg9dF6sKjQ&lib=M7v_2CxFrrqdcmzthOkMrc1jilJU4QU4H');
void getData() async {
Response response = await get(url);
if(response.statusCode == 200) {}
var feedback = convert.jsonDecode(response.body);
print('Response body: ${response.body}');
}
when i'm printing the response body,i'm getting the whole data
now,what i'm trying to do is to enter a number to a TextField in the flutter app
and to get a result from the parallel second column next to the first column where is typed the number i entered.
=============================
update
i've created a model from my json data
this the model created from the website
https://javiercbk.github.io/json_to_dart/
class Note {
late String id;
Note({required this.id});
Note.fromJson(Map<String, dynamic> json) {
id = json['id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
return data;
}
}
now this the new code for getting the data from google sheet
Future<void> getData() async {
var response = await http.get(Uri.parse(
"https://script.google.com/macros/s/AKfycbzU89ZEE0Y9sgEQZMZHSbX00M6hPdHOX6WN8IjQWa5lzgAzmAc4jZShpUfKbnJ5zm8J/exec"));
var body = response.body;
Note note = Note.fromJson(jsonDecode(body));
print(note.id.toString());
}
and i'm getting an error when trying to run the flutter app on vscode
a new tab of browser client opened no data come from the google sheet api
and this a screenshot from the vscode
While working with JSON data
The good practice is to create a model for that and then just fetch the data through the API
creating a model and a class is easy enough and doesn't take effort and makes your work easy ;)
For creating a model for your project
VISIT https://javiercbk.github.io/json_to_dart
Just copy your JSON data and paste in the textField and you will get your Model Class ready with just one click
for accessing the data
Test _test = Test.fromJson(response.body);
that's it.
refer image shown below
Related
I'm a junior working with flutter and hit a problem.
I need to open a file, read and compare some data everytime the app opens and then change some of that data as the app progress. We tried using .txt files to read and write some text, but when we had to look for something in the file was too complicated to change it and the file is not accessibe only on the device running the app. We also thought of using xml files but I don't know if is a good idea.
What would be a pratical solution for this situation, as the file needs to be opened all the time. Thanks.
Let's say our JSON looks like this:
{
title: 'some text',
values: [1,5,2,4,1,3],
}
And we want to make a UI that allows us to add values and to edit the title. First let's write a method to write and read from the JSON file:
Future<void> _write(Map<String, dynamic> value) async {
File f = File(_fileLocation);
String jsonStr = jsonEncode(value);
await f.writeAsString(jsonStr);
}
Future<Map<String, dynamic>> _read() async {
File f = File(_fileLocation); // maybe move this into a getter
final jsonStr = await f.readAsString();
return jsonDecode(jsonStr) as Map<String, dynamic>;
}
This way, the rest of the app should be trivial, but let's add a method to update the title and a method to add a new number:
Future<void> _updateTitle(String title) async {
var values = await _read();
values['title'] = title;
await _write(values);
}
Future<void> _addNumber(int number) async {
var values = await _read();
values['values'].push(number);
await _write(values);
}
Types with JSON and Dart can be a bit weird, so it is possible you need to use the as keyword when reading from the list:
Future<void> _addNumber(int number) async {
var values = await _read();
var valueList = (values['values'] as List<int>);
valueList.push(number);
values['values'] = valueList;
await _write(values);
}
Hopefully, this example helps
Do we have to use different google map API keys for each iOS, android, and place autocomplete?
currently, I am using one API key for all like this
and something is not working. the map suggests me the name of the locations when I type in the search text field, but I get the error when I tap on the name of the location. the error says
Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>' in typecast
I think I am doing something wrong with the API keys.
Do we have to use different keys for each platform?
here is my http request
Future<String> getPlaceId(String input) async {
final String url =
'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=$input&inputtype=textquery&key=$autocompletekey';
final response = await http.get(Uri.parse(url));
var json = convert.jsonDecode(response.body);
var placeId = json['candidates'][0]['place_id'] as String;
print(placeId);
return placeId;
}
Future<Map<String, dynamic>> getPlace(String input) async {
final placeId = await getPlaceId(input);
final String url =
'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?place_id=$placeId&key=$autocompletekey';
final response = await http.get(Uri.parse(url));
var json = convert.jsonDecode(response.body);
var results = json['result'] as Map<String, dynamic>; // this line of code produces error
print(results);
return results;
}
I'm using real time database for posting and getting of data in my app.
Everything is fine but when I restart app, data is not showing in app.
Posted data is showing in database on restart but not showing on restart.
Here I'm posting data on database:
Future<void> addTask(String newTaskTitle) async {
final task = Task(title: newTaskTitle);
const Url = ''// used url but hiding it here;
await http.post(Url, body: json.encode({
'title': task.title,
}),);
tasks.add(task);
notifyListeners();
}
Here I'm getting data from database:
Future<void> fetchAndSetData() async {
const Url = ''// used url but hiding it here;
var response = await http.get(Url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final List<Task> loadedTasks = [];
extractedData.forEach((taskID, taskData) {
loadedTasks.add(Task(
id: taskID,
title: taskData['title'],
));
});
tasks = loadedTasks;
notifyListeners();
}
When you render your app for the first time then call fetchAndSetData() in initState() function, with this the data that you stored in the database will be fetched before the actual rendering of widget tree.
I am making a flutter application in which in need to fetch data from backened API which is made in wordpress.Now in postman i only need to insert client key and client secret in Oauth 1 authentication and it works fine.But in flutter application it tell that the signature data is invalid.Why ?
I followed official guide from woocommerce Api but i failed.How can i make wordpress api in flutter in dart?I am new to flutter and this is very important for me.So how can i fetch data ?Is there any method to achieve what i want ?
As per my understanding, you are looking for something like this
You want to display the products from wooCommerce using REST API.
And you want that to be done in Flutter Dart.
Auth for users.
The very first thing will do is Auth the user using Username and Password so to do that we have to do something like this
For Auth you should install the JWT plugin name JWT Authentication for
WP-API in WordPress
Then use this URL in the Flutter
Future<http.Response> login(String username, String password) async {
final http.Response response = await http.post('https://domina-name/wp-json/jwt-auth/v1/token?username=abc&password=xyz');
print(response);
return response;
}
This function fetches the data from the wooCommerce REST API endpoints and stores in the List
List<CatService> category;
Future<void> getCategoryData() async {
var res = await http.get(
"https://domain-name/wp-json/wc/v3/products/categories?per_page=100&consumer_key=xxxxxxxxxxxxxxxxxxxxx&consumer_secret=xxxxxxxxxxxxxxx&page=1");
setState(() {
var data = json.decode(res.body);
var list = data as List;
print("List of cat $list");
categoryList =
list.map<CatService>((json) => CatService.fromJson(json)).toList();
category = categoryList
.where((data) => data.count > 0 && data.catName != 'Uncategorized')
.toList();
});
}
Now you should call this future getCategoryData method like this
void initState() {
setState(() {
this.getCategoryData();
});
super.initState();
}
I have created a class for CatService
class CatService {
int catId;
String catName;
int count;
CatService({this.catId, this.catName,this.count});
factory CatService.fromJson(Map<String, dynamic> json) {
return CatService(catId: json['id'], catName: json['name'],count: json['count']);
}
}
Thanks, I hope this will help you
I want to create dynamic forms and fetch data after submitted form. I have an API and I'm getting questions from this API. In application, user will answer questions and save the result to API. How can I create dynamic forms and retrieve user inputs. Please help.
FutureBuilder<List<ConditionType>>(
future: _api.getConditionTypes(job.sectorId),
builder: (context, snapshot) {
//Create Form
}
Try using json_to_form, If you could share the structure of the response I could assist to tweaking the plugin which I had to do for my own project. I should mention that with this implementation DropDownButton tends to have issues displaying values though it saves them.
I make the Json tranforms making the model of the object and then make the request:
class Model {
String projectName;
String datePlan;
String activityName;
String hours;
TimeSheetModel({this.projectName, this.datePlan, this.activityName, this.hours});
TimeSheetModel.fromJson(Map<String, dynamic> json){
projectName = json["ProjectName"];
datePlan = json["DatePlan"];
activityName = json["ActivityName"];
hours = json["Hours"];
}
Map toMap() {
var map = new Map<String, dynamic>();
map["ProjectName"] = projectName;
map["DatePlan"] = datePlan;
map["ActivityName"] = activityName;
map["Hours"] = hours;
return map;
}
}
The method fromJson transforms Json data to your object for GET request and toMap tranform your object to Json for POST or PUT request.
Making the GET request:
getProjects() async {
var url = 'url';
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json",
"charset": "UTF-8"});
data = json.decode(res.body);
setState(() {
Model data = Model.fromJson(resBody);
});
}
Making the POST request:
post() async {
var url = 'url';
http.post(url, body:
data.toMap()).then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
}