Make specific words from JSON String clickable Flutter - json

I have a JSON response where i am getting some questions. Now after getting those questions i want to split them into words and match those words with another JSON response and on match i want to highlight those words and make them clickable so i can show a pop up which contains that word's translation which is present in my 2nd response. At the last i want to show both matched and unmatched words together just like it was a question before but with clickable words.
This is what i want
this is my first json
"status": "true",
"message": "message",
"demo": [
{
"qtnNumber": 1,
"qtnItalian": "Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
},
{
"qtnNumber": 2,
"qtnItalian": "Il segnale strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
},
this is my second json
{
"status": "true",
"message": "Vocabulary",
"vocabulary": [
{
"id": 3406,
"italian": "a condizione ",
"punajbi": "ਹਾਲਾਤ ਕੰਡੀਸ਼ਨ",
"english": "condition",
"number": null,
"punjabiEnglish": "halat",
},
{
"id": 3407,
"italian": "a raso",
"punajbi": "ਪਲੇਨ ਇਸ ਦਾ ਬੁੱਕ ਵਿੱਚ ਪੂਰਾ ਲਫ਼ਜ਼ ਹੇ incrocio a raso => ਇਸ ਦਾ ਮਤਲਬ ਪਲੇਨ ਚੌਕ ਇੱਕੋ ਲੈਵਲ ਤੇ ਬਣਿਆ ਹੋਇਆ ਚੌਕ",
"english": "plane",
"number": "ikO LEVEL DA CHONK",
"punjabiEnglish": null,
},
{
"id": 3408,
"italian": "accesso",
"punajbi": "ਦਾਖਿਲ",
"english": "Entry",
"number": null,
"punjabiEnglish": "Dakhil",
}
now from first json after splitting each question into words i want to match those words with my 2nd json 'italian' field and if matched i want to highlight those words

import 'dart:convert';
const raw_sentences = '''
{
"status": "true",
"message": "message",
"demo": [
{
"qtnNumber": 1,
"qtnItalian": "Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
},
{
"qtnNumber": 2,
"qtnItalian": "Il segnale strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
}
]
}
''';
const raw_vocabulary = '''
{
"status": "true",
"message": "Vocabulary",
"vocabulary": [
{
"id": 3406,
"italian": "a condizione ",
"punajbi": "ਹਾਲਾਤ ਕੰਡੀਸ਼ਨ",
"english": "condition",
"number": null,
"punjabiEnglish": "halat"
},
{
"id": 3407,
"italian": "a raso",
"punajbi": "ਪਲੇਨ ਇਸ ਦਾ ਬੁੱਕ ਵਿੱਚ ਪੂਰਾ ਲਫ਼ਜ਼ ਹੇ incrocio a raso => ਇਸ ਦਾ ਮਤਲਬ ਪਲੇਨ ਚੌਕ ਇੱਕੋ ਲੈਵਲ ਤੇ ਬਣਿਆ ਹੋਇਆ ਚੌਕ",
"english": "plane",
"number": "ikO LEVEL DA CHONK",
"punjabiEnglish": null
},
{
"id": 3408,
"italian": "accesso",
"punajbi": "ਦਾਖਿਲ",
"english": "Entry",
"number": null,
"punjabiEnglish": "Dakhil"
},
{
"id": 3500,
"italian": "preannuncia"
},
{
"id": 3501,
"italian": "consentita"
}
]
}
''';
void main(List<String> args) {
var sentence = jsonDecode(raw_sentences)['demo'][0]['qtnItalian'] as String;
var vocabulary = jsonDecode(raw_vocabulary)['vocabulary'] as List;
var words = sentence.split(' ');
var matches = vocabulary.map<String>((m) => (m as Map<String, dynamic>)['italian']).toSet().intersection(words.toSet()).toList();
var references = Map.fromEntries(List.generate(matches.length, (i) => MapEntry(matches[i], vocabulary.firstWhere((m) => m['italian'] == matches[i])['id'])));
var new_sentence = <Map<String, dynamic>>[];
var idx = 0;
words.forEach((word) {
if (matches.contains(word)) {
new_sentence.add({'string': word, 'reference': references[word]});
idx += 2;
} else {
if (new_sentence.isEmpty || idx == new_sentence.length) new_sentence.add({});
new_sentence[idx]['string'] = (new_sentence[idx]['string'] ?? '') + ' $word';
}
});
print(sentence);
print(new_sentence);
}
Result:
Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia
[{string: Il segnale raffigurato}, {string: preannuncia, reference: 3500}, {string: un tratto di strada in cui è}, {string: consentita, reference: 3501}, {string: la manovra di retromarcia}]
With the new_sentence list you can create widgets (texts and buttons) to get your goal, that is the easy part and it is your work. Remember, this site is for help, it is not to do your whole work. Good day.

Related

object Angular to array

How can I get only the data array from the observable response ?, I need to get the values ​​of cat_id,cat_name,cat_description but not the sql_types array
{
"code": 0,
"message": "",
"data": [
{
"cat_name": "Topografía",
"cat_description": "Servicios de topografía en general",
"cat_id": 1
},
{
"cat_name": "Estructuras hormigón",
"cat_description": "subcontratas de estructuras de hormigón ",
"cat_id": 3
}
],
"sqlTypes": {
"cat_name": 12,
"cat_description": 12,
"cat_id": 4
}
}
You can pipe your observable and map it to the object you want.
Only your data will be availible in the example below
Observable.pipe(map(resp => resp.data)).subscribe(data=> //do something)

Create and retrieve "multi-level" data in JSON

For a course exercise, a friend of mine has to dynamize a website with a JSON. The problem occurs when I try to search for data on several levels. Basically, Elles wants to allow to choose ornaments. There are handles or screw covers available, and there are two of each. The problem is that I can't properly structure my JSON to make this possible, or to retrieve the data.
{
"id" : 4,
"nom":"Cercueil Les Borgia",
"description": "Ce cercueil demi-tombeau en chêne massif , vous propose de le personnaliser en s'inspirant des jardins les plus fleuris mais aussi les plus dangereux",
"prix" : 800 ,
"image" :"medias/chenemassif1.png" ,
"motifs":
[
{
"natureMo":"Fleur",
"prixMo": "30",
"disponibiliteMo":true
},
{
"natureMo":"Vichy",
"prixMo": "30",
"disponibiliteMo":true
}
],
"couleurs":
[
{
"nomCo": "Vert clair",
"code": "#93C97F"
},
{
"nomCo": "Violet",
"code": "#64527A"
}
],
"ornements": [
{
"types": [
{
"Poignées": [
{
"style": "Romaine",
"prixOr": 22,
"disponibiliteOr":true
},
{
"style":"Flamme Eco",
"prixOr":22,
"disponibiliteOr":true
}
]
},
{
"Cache-vis" : [
{
"style":"Roseau",
"prixOr":18,
"disponibiliteOr":true
},
{
"style":"Hexagonale",
"prixOr":18,
"disponibiliteOr":false
}
]
}
]
}
]
}
I've tried to put both ornament types in one type category, and use it, but that doesn't work either when I try to retrieve the data.
res += '<h3>Ornements</h3>';
for(l=0; l<doc[i].ornements.length; l++){
var ornementsNaCer = doc[i].ornements[l].types;
res += '<h4>'+ ornementsNaCer +'</h4>';

Flutter l10n - Dynamic key

I am actually coding a multi-language app and I have a problem to get my resources on different languages. My app is currently working on one language with a json file.
For example I got :
{
"Resorts" : [
{
"name": "Walt Disney World Resort",
"slug": "waltdisneyworldresort",
"description": "Explorez des terres d'enchantement infini, où vos fantasmes deviennent réalité !"
},
{
"name": "Disneyland Resort",
"slug": "disneylandresort",
"description": "Regardez les rêves devenir réalité dans l'endroit le plus heureux de la planète !"
},
]
}
I started using l10n and I have my files app_en.arb:
{
"##locale": "en",
"resortDesc": "English description",
"#resortDesc": {
"description": "Description of the resort that will be displayed on the cards in the Resort Selection screen",
}
}
and app_fr.arb:
{
"##locale": "fr",
"resortDesc": "Description en Français",
"#resortName": {
"description": "Description du resort qui sera affiché sur la page 'Resort Selection'",
}
}
But this means that I need to call my texts with something like:
AppLocalizations.of(context)!.resortDesc
While I was calling my texts from my json as:
Future<void> readJsonDatas() async {
final String res = await rootBundle.loadString("assets/datas.json");
final data = await jsonDecode(res);
setState(() {
datas = data;
});
await datas;
for(var data in datas['Resorts']) {
parks.add(
Resort(name: data['name'], imagePath: data['image'], slug: data['slug'], bgImagePath: data['bg_image'], description: data['description'], parks: data['parks'] ?? [], lat: data['latitude'], long: data['longitude'])
);
}
currentResort = parks[0]; // Default park
}
Do you have any idea what I could do in app_en.arb and app_fr.arb to get my datas as:
AppLocalizations.of(context)!.datas['slug'].description
Or how I should do it ?
Many thanks for your tips,
Have a great day !

React-native Flatlist doesn't list my json local file

I met an issue with my Flatlist in Board.js which doesn't display the content of a json data located inside a file BoardData.js.
However I ve console.log the import of the BoardData and seems the json isfine.But when Istart to read on some data via the flat list. the data are undefined.
See my BoardData.js file :
var BoardData = [
{
"id":"1",
"status": "declared",
"date": "03-DEC-2019",
"category": "Fuite d'eau",
"event_info": "Contact du Plombier",
"adress": "2 rue de la queuleuleu, 31200 Toulouse",
"imageUrl": "..data/photo/photo_123456.webp"
},
{
"id":"2",
"status": "run",
"date": "12-JAN-2020",
"category": "eclairage",
"event_info": "Contact du Plombier",
"adress": "3 impasse alphonse-daudet, 31700 Blagnac",
"imageUrl": "../data/photo/photo_234459.jpg"
},
{
"id":"3",
"status": "declared",
"date": "20-FEB-2020",
"category": "chaussee",
"event_info": "Contact du Plombier",
"adress": "50 avenue de Fronton, 31140 Aucamville",
"imageUrl": "../data/photo/photo_458049.jpg"
},
{
"id":"4",
"status": "closed",
"date": "04-DEC-2019",
"category": "Poubelle",
"event_info": "Contact du Plombier",
"adress": "3 rue de la queuleuleu, 31200 Toulouse",
"imageUrl": "../data/photo/photo_123456.webp"
},
{
"id":"5",
"status": "closed",
"date": "13-JAN-2020",
"category": "Ascenceur",
"event_info": "Contact du Plombier",
"adress": "4 impasse alphonse-daudet, 31700 Blagnac",
"imageUrl": "../data/photo/photo_234459.jpg"
},
{
"id":"6",
"status": "run",
"date": "21-FEB-2020",
"category": "chaussee",
"event_info": "Contact du Plombier",
"adress": "52 avenue de Fronton, 31140 Aucamville",
"imageUrl": "../data/photo/photo_458049.jpg"
},
];
module.exports = BoardData;
Then see my code to render my FlatList:
import React, { Component } from 'react';
import {
FlatList, ScrollView, StyleSheet, Platform, View, Image, Dimensions, TouchableOpacity,
} from 'react-native';
import {Card, CardItem, Left, Right, Thumbnail, Title, Subtitle} from 'native-base';
import BoardData from '../data/BoardData.js'
console.log ('BoardData : ', BoardData)
export default class BoardScreen extends Component {
constructor(){
super();
this.state = {
boarderstatus: 'declared',
myCases: [],
}
}
componentDidMount () {
this.setState({myCases:BoardData })
}
// Synchronization concerning the gesture
async setBoarder(value){
console.log("SETBoarder value : " + value)
this.setState({boarderstatus:value })
console.log("SETBoarder boarderstatus : " + value)
}
renderCard(item,index){
if (item.category === this.state.boarderstatus)
{
return (
<TouchableOpacity styles={style.btn}>
<Card>
<CardItem>
<Left>
<Thumbnail
source={require('../data/photo/photo_234459.jpg')}
style={{width:80,height:80}}/>
<Block left style={{top:-15, left:5}}>
<Title>{item.category}</Title>
<Subtitle>{item.date}</Subtitle>
</Block>
</Left>
<Right>
<Block>
</Block>
</Right>
</CardItem>
</Card>
</TouchableOpacity>
);
}
}
render() {
return (
...
<FlatList
data={BoardData}
keyExtractor={(item)=>item.id}
renderItem={(item, index) => this.renderCard(item, index)}
/>
);
}
}
Ok Fix :
Just instance BoardData json object to BoardData here is the code:
<FlatList data={BoardData.BoardData}
keyExtractor={(item)=>item.id}
renderItem={(item, index) => this.renderCard(item, index)}/>

Limitation in the number of posts to fetch with Blogger API (error 400)

I am trying to fetch all the post from a blog using the Blogger API. The maximum number of posts to fetch seems to be limited to 20 for some unknown reasons.
If I try this URL:
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?maxResults=20&fields=items(title)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
I get the following response (listing the last 20 post titles as expected):
{
"items": [
{
"title": "El Caballero"
},
{
"title": "Une traversée de frontière… étonnante!"
},
{
"title": "Hasta luego querida Argentina!"
},
{
"title": "Dernier jour en Argentine"
},
{
"title": "Humahuaca"
},
{
"title": "Purmamarca"
},
{
"title": "Tilcara"
},
{
"title": "Premières grèves"
},
{
"title": "Le Nord Argentin: Salta"
},
{
"title": "Ca en fait de l'eau tout ça..."
},
{
"title": "Un peu de pluie au Brésil"
},
{
"title": "Iguazu"
},
{
"title": "San José"
},
{
"title": "Adieu à Buenos Aires"
},
{
"title": "Traversons en Uruguay"
},
{
"title": "Retour à Buenos Aires"
},
{
"title": "Fin de l'aventure Patagonienne"
},
{
"title": "Les fameuses tours nous surprennent"
},
{
"title": "Un peu de pluie pour se changer les idées"
},
{
"title": "Valle Francés"
}
]
}
However, if I increase the maxResults parameters,
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?maxResults=21&fields=items(title)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
I get the following error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
How could I increase the limitation in the maximum number of post that I can fetch?
Thanks,
Nicolas
I think that the API is limited to only pull 20 results as a maximum.
So in order to fetch more than 20 results you have to use the pageToken parameter as specified in Bloggers's reference API.
Your first request should include the nextPageToken so you will have it in the response. Than use this token to retrieve the next page and so on.
Your first request must be like this :
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?maxResults=20&fields=items%28title%29%2CnextPageToken&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
Here is the expected result :
{
"nextPageToken": "CgkIChignPaz5ycQ-rn0pIfipe8q",
"items": [
{
"title": "El Caballero"
},
{
"title": "Une traversée de frontière… étonnante!"
},
{
"title": "Hasta luego querida Argentina!"
},
{
"title": "Dernier jour en Argentine"
},
{
"title": "Humahuaca"
},
{
"title": "Purmamarca"
},
{
"title": "Tilcara"
},
{
"title": "Premières grèves"
},
{
"title": "Le Nord Argentin: Salta"
},
{
"title": "Ca en fait de l'eau tout ça..."
}
]
}
Now all you have to do is to pick the "nextPageToken": "CgkIChignPaz5ycQ-rn0pIfipe8q" in the result and include it in you next request like this :
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?%20maxResults=20&pageToken=CgkIChignPaz5ycQ-rn0pIfipe8q&fields=items%28title%29%2CnextPageToken&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
The result should show the next 20 posts in addition to a new ``nextPageToken` to use in the next request.
I implemented what was suggested by Walid Laribi for a travel blog page that retrieve the location of all the posts from the blog and draw the path taken during the travel (blog).
To fetch the location of all the posts, I have first a script that retrieves the first 10 posts and gives me the nextPageToken:
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?fields=nextPageToken,items(title,location(name,lat,lng),url,published)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU&callback=handleResponse">
In the callback of the previous script, we can get the location of each post as well as creating and executing the script to fetch the next posts:
// Get latitude/longitude from Blogger
function handleResponse(response) {
for(i=0; i< response.items.length; i++){
if(response.items[i].location != undefined){
Lat.push(response.items[i].location.lat);
Lng.push(response.items[i].location.lng);
// etc.
}
}
if(response.nextPageToken != undefined){
var srctxt = 'https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?fields=nextPageToken,items(title,location(name,lat,lng),url,published)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU&callback=handleResponse&pageToken=' + response.nextPageToken;
// Execute the new script
var head = document.getElementsByTagName('head')[0];
var scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.setAttribute('src', srctxt);
head.appendChild(scriptElement);
head.removeChild(scriptElement);
}
}