Codings

Implementa l’App per il tuo canale Youtube con Flutter in 10 minuti

Con questo articolo voglio spiegare come poter fare una app per il proprio canale personale youtube in 10 minuti. Io ho sviluppato in questo modo l’app Italiano con Eli, creata per il canale Italiano con Eli. Mentre stavo sviluppato l’app ho deciso di generalizzare la soluzione in modo da poter essere utilizzata da chiunque per recuperare qualsiasi video dato un determinato link del corrispettivo canale Youtube. L’applicazione completa e funzionante è disponibile al seguente link github. Potete fare un Fork o un Clone, usarla così com’è oppure modificandola come meglio vi pare. Se vi piace potete anche mettere un like. Configurazione necessaria Unica cosa da fare per poterla utilizzare è configurare la connessione alle API di Youtube in modo da poter utilizzare la ricerca dei vostri video del canale. Per una corretta configurazione potete seguire i seguenti step: Accedere al Google Api Console con il vostro account Google se non lo avete, create un nuovo account. Andare sotto progetti e cliccate su NUOVO PROGETTO, Immetti il nome e aspetta che google crei il progetto. Clicca sul link delle Google API nella libreria delle API e cerca oppure seleziona le api youtube come evidenziato nella foto di seguito dopo clicca abilità e vai sotto la voce di menu credenziali Seleziona Youtube Api v3, seleziona dati pubblici e conferma Adesso Google creerà la tua chiave di accesso l’api key recuperata al punto 6 dovrà essere inserita all’interno dell’applicazione e sostituita nella pagina main.dart al posto della key come segue: static String key = ""; // ** ENTER YOUTUBE API KEY HERE ** static String channelid = "UC_8mNVpafplqHNy85No4O2g"; // ** ENTER YOUTUBE CHANNEL ID HERE ** il channel id deve fare riferimento al vostro canale youtube. Lo potete semplicemente estrarre dal link del vostro canale youtube, prendendo la parte finale del link: La configurazione è finita, avete appena creato la vostra nuova App per il vostro canale Youtube Yehaa! Qualche cenno al codice Per agevolare lo sviluppo dell’applicazione ho usato i seguenti due plugin che potete trovate nella pagina dei plugin per flutter flutter packages i plugin utilizzati sono i seguenti: youtube player Flutter youtube Api il codice dell’applicazione è molto semplice e ho usato una struttura di suddivisione pagine abbastanza chiara: Model contiene il modello dei dati recuperati dalle youtube Api. Adesso la classe fa anche qualcosa in più, c’è un metodo che recupera i dati da youtube e li inserisce in una lista di youtube data. Usa un sistema che fa il recupero dei dati solo se non sono presenti in cache usando la flutter shared preference. Questo meccanismo è molto utile in quanto le Api di Google sono a pagamento in funzione dell’utilizzo. Utilizzando la cache risparmierete drasticamente in chiamate. se non avete mai usato la cache in flutter potete leggere quest’altro mio articolo: flutter shared preferences in profondità. Pages contiene le pagine dell’APP home page category page pagina di play video UI contiene un widget per rappresentare la lista dei video. L’ho creato a parte come widget per avere a disposizione una view da poter utilizzare sia nella pagina home che category. In questo modo, potrei usarlo anche in altre pagine in futuro. Main.dart altro non fa che inizializzare la classe del model, caricare i dati di youtube e passarli alle rispettive pagine. Utilizzando questa struttura il codice è molto semplice anche da manutenere ad esempio la pagina home contiene solo il seguente codice: import 'package:flutter/material.dart'; import 'package:youtubeapichannel/Model/YoutubeData.dart'; import 'package:youtubeapichannel/UI/YoutubeVideoList.dart'; YoutubeData youtubeData; class Home extends StatefulWidget { Home(YoutubeData inyoutubeData) { youtubeData = inyoutubeData; } @override _HomeState createState() => new _HomeState(); } class _HomeState extends State<Home> { callAPI() async { setState(() {print('UI Updated'); }); } @override void initState() { super.initState(); //callAPI(); } @override Widget build(BuildContext context) { if(youtubeData!=null) return new YoutubeVideoList(youtubeData.getHomeList()); else return new Container(child:new Text("problem loading data from youtube!")); } } Quindi riceve semplicemente in input la classe contenente la lista dei video e richiama il plugin YoutubeVideoList che sta sotto la UI per rappresentare i video sotto forma di lista di video youtube. Unica pecca, è che quando l’ho realizzata non ero tanto esperto e ho deciso di passare i dati come parametro. Oggi flutter mette a disposizioni tecniche migliori per passare i dati da una view ad un altra, in effetti dovrei fare un po' di refactor, ma oggi non ne ho voglia.

Youtube Channel Android and Ios APP in ten minute with Flutter

With this article I want to explain how to build an app for your personal youtube channel in 10 minutes. I did this basic project to create Italiano con Eli app, created for the YouTube channel Italiano con Eli. While I was developing the app I decided to generalize the solution so that it can retrieve any video to any Youtube channel. The complete and working application is available at the following link github. You can make a Fork or a Clone or use it as it or by modifying it as you like. If you like you can also put a like to my git project. Required configuration The only thing to do to be able to use it is to configure the connection to the Youtube API so that you can use the search for your channel videos. For a correct configuration you can follow the following steps: Log in to the Google Api Console with your Google Account if you don’t have it, create a new account. Go under projects and click on NEW PROJECT, enter the name and wait for google to create project. Click on the link in the Google API library and search or select the youtube API as highlighted in the photo below after click ability and go under the credentials menu item Select Youtube Api v3, select public data and confirm Now Google will create your api key the api key recovered in step 6 will be inserted within the application and replaced the page main.dart instead of the key as follows: static String key = ""; // ** ENTER YOUTUBE API KEY HERE ** static String channelid = "UC_8mNVpafplqHNy85No4O2g"; // ** ENTER YOUTUBE CHANNEL ID HERE ** the channel id must refer to your youtube channel. You can simply extract it from the link of your youtube channel, taking the final part of the link: The configuration is finished, you have just created your App for your personal Youtube channel! Yehaa! Some references to the code To facilitate the development of the application I used the following two flutter plugins that you can find on flutter packages pages. The plugins used are the following: youtube player Flutter youtube API the application code is very simple and I have given apage division structure fairly clear: Model contains the model of data recovered from API youtube. Now the class also does something more, there is a method that also retrieves the data from youtube and inserts it in the model and some method to recover the data. There is also a system that recovers data only if it is not cached using the shared preference flutter. This mechanism is very useful as the Google API is paid according to the use. Using the cache will save you drastically in calls. if you have never used the cache in flutter you can read this mine other article: flutter shared preferences in depth. Pages contains the APP pages home page category page play video page UI contains a widget to represent the list of videos. I created it separately as a widget to create a view that can be used on both the home page and category and I could also use it in other pages in the future. **Main.dart ** just to initialize view, the model class, load the youtube data and pass it to the respective pages. Using this structure, the code is very simple to maintain, for example the home page contains only the following code: import 'package:flutter/material.dart'; import 'package:youtubeapichannel/Model/YoutubeData.dart'; import 'package:youtubeapichannel/UI/YoutubeVideoList.dart'; YoutubeData youtubeData; class Home extends StatefulWidget { Home(YoutubeData inyoutubeData) { youtubeData = inyoutubeData; } @override _HomeState createState() => new _HomeState(); } class _HomeState extends State<Home> { callAPI() async { setState(() {print('UI Updated'); }); } @override void initState() { super.initState(); //callAPI(); } @override Widget build(BuildContext context) { if(youtubeData!=null) return new YoutubeVideoList(youtubeData.getHomeList()); else return new Container(child:new Text("problem loading data from youtube!")); } } Then simply receive the class containing the list of videos as input and call the YoutubeVideoList plugin that is under the UI to represent them in the form of a list of YouTube videos. The only flaw is that when I made it I was not so expert and I decided to pass the data as a parameter. Today flutter offers better technical provisions for passing data from one view to another, in fact I should make an update and do the usual refactor.

Risparmio tempo = faccio più cose

Noi programmatori abbiamo diverse competenze e tanti pattern che utilizziamo, ma credo che la cosa che maturiamo nel tempo e ci accomuna di più è l’ottimizzazione delle risorse per risparmiare tempo. Tutti sanno che il tempo è la cosa più importante! Lo dice lo stesso modo di dire: il tempo è denaro. Il detto si basa su tempo umano. Il tempo umano deve essere utilizzato come valore aggiunto per la creatività, invenzione, innovazione costruzione e implementazione. Noi programmatori siamo fortunati, abbiamo a disposizione un’altra unità di misura del tempo, oggigiorno tendente quasi all’infinito, che possiamo e dobbiamo sfruttare al massimo e questo tempo e il tempo macchina. Un tempo si facevano fatigare gli schiavi poi i cavalli, i muli, i motori oggi ci siamo evoluti, culturalmente e mentalmente, Gli schiavi di quest’era sono le macchine. Per macchine intendo i nostri pc, o meglio ancora i nostri server, il cloud o i robot. Ho deciso di scrivere questo articolo per riportare delle tecniche utili per efficientare il nostro lavoro e di conseguenza ottenere più tempo. La mia tecnica principale da utilizzare per ottenere questo risultato è: appuntare gli step manuali che compiamo per fare un compito ricercare possibili soluzioni alternative riflettere su come possiamo automatizzare ogni singolo step mettere tutto assieme ripartire dal punto 1 se il nostro tempo d’impiego non è ancora = 0 per l’attività scelta Un esempio Spesso per velocizzare il nostro lavoro scriviamo degli script, questi script sono necessari altrimenti dovremmo scrivere n istruzioni di comandi. Giornalmente o mensilmente o dopo aver fatto qualcos’altro, dobbiamo eseguirli. Quindi apriamo il terminale e lanciamo lo/gli script. Per evitare di lanciare lo script a mano, che implica ricordarci, trovare lo script e lanciarlo, possiamo procedere nel seguente modo: se si tratta di qualcosa che va eseguito con una schedulazione fissa possiamo schedularlo utilizzando uno scheduler in linux possiamo fare un cron oppure possiamo utilizzare atrigger per eseguire la schedulazione nel caso in cui il nostro script sia su un server a cui non abbiamo accesso alla schedulazione Se invece non c’è una schedulazione fissa e dobbiamo eseguirlo al bisogno Possiamo utilizzare una scorciatoia da tastiera. In linux ma anche su Windows e molto semplice settare una una scorciatoia. Nel mio caso usando Ubuntu basta andare sotto *impostazioni *-> scorciatoie da tastiera e aggiungiamo il nostro nuovo parametro che conterà il path al nostro script e la scorciatoia desiderata. Come potete vedere nella seguente immagine, io lo uso ad esempio per lanciare in debug il mio blog e successivamente per fare il deploy: per quanto questo possa sembrare bello e può aiutarci a renderci più efficienti, con due tasti, il gioco è fatto, si può sempre ottimizzare. Voi direte, che altro puoi fare per ottimizzare questo? e perchè? Il perchè è semplice, per poterlo eseguire ho necessariamente bisogno di avere la mia macchina a disposizione e accesa. Quindi sarebbe meglio laddove possibile utilizzare sempre un server o il cloud in modo da fare tutto da remoto in modo così da poter avere più controllo e soprattutto non dipendere da una macchina. Oggi ci sono tanti strumenti che abbiamo a disposizione per eseguire script o creare piccole pagine web o piccole applicazioni o siti vetrina. Il piano gratuito di questi servizi, mette a disposizione tanti strumenti fra i quali: Spazio hosting. Spazio database. Funzioni per micro servizi Container Macchine virtuali e chi più ne ha più ne metta C’è ne sono così tanti che a volte tendiamo a non vederli, nonostante siano sotto il nostro naso. Quelli che utilizzo io maggiormente, sono: Firebase Google Cloud Amazon AWS Google Script L’ultimo servizio a differenza degli altri non è un servizio cloud ma semplicemente un motore di funzioni con schedulazione o attivazione in funzione dei servizi Google. Sono molto integrate con il nostro account Google e se lo usiamo come mail principale ci darà davvero delle grandi potenzialità per automatizzare: invii di mail sincronizzazione di dati editing di documenti chiamare API esterne memorizzare dati in excel ecc ecc… è brutto dire ecc ecc ma davvero, l’elenco sarebbe troppo lungo, vi permette di automatizzare tutto ciò che è Google. Gli altri tre sono i primi tre migliori provider Cloud. Per cominciare io consiglio di usare Firebase perchè mette a disposizione davvero tanti servizi e se si tratta di primo inzio con il cloud, l’accesso con Firebase, credo sia più semplice e con una linea di apprendimento più rapida. Conclusioni Cerchiamo di fare più attenzione a quello che ogni facciamo senza pensare. Se ogni giorno facciamo una cosa ripetitiva, anche se ci mettiamo davvero poco a farla, teniamola in considerazione e pensiamoci. Dopo anni le cose ripetitive possono diventare tante e rischiamo di saturare tutto il nostro tempo col fare solo cose ripetitive. Vi lascio e vi saluto con una frase che mi è venuta adesso. Probabilmente non ha senso o forse è già di qualcuno ma io non lo so. Meglio creare un sistema che ci risolve un problema che risolvere il problema stesso!

save time = do more things

We as programmers have different skills and we use lot of patterns, but I think the thing that we mature over time and we have more in common is the resources optimization for time saving. Everyone knows that time is the most important thing! The same way of saying it: time is money. The saying is based on human time. Human time must be used as an additional value for creativity, invention, construction innovation and implementation. We programmers are lucky, we have another measurement time unit, nowadays almost tending to infinity. This is machine time and we have to make the most of it. Once we used slaves, then horses, mules, engines motor. Today we have evolved, culturally and mentally. The slaves of this era are machines. By machines I mean our PCs, or better yet our servers, the cloud or robots. I decided to write this article to report useful techniques to make our work more efficient and consequently have more time. My main technique to be used to obtain this result is: write down the manual steps that we perform to do a task search for possible alternative solutions reflect on how we can automate each single step put everything together starting from point 1 if our time for the task is not equal to 0 An example Often to speed up our work we write scripts, these scripts are necessary otherwise we would have to write n command statements. Daily or monthly or after doing something else, we have to do it. So let’s open the terminal and run the scripts. To avoid launching manual the script, which implies remembering, finding the script and launching it, we can proceed in the following way: if it is something that must be done with a fixed date Schedule it using a scheduler With linux, we can make a cron We can use atrigger to execute the scheduling in the event that our script is on a server to which we do not have access to server side If instead there is no fixed scheduling date and we have to execute it as needed We can use a keyboard shortcut. In linux but also on Windows it is very simple to set a shortcut. In my case using Ubuntu just go under *settings *-> keyboard shortcuts and add our new parameter that will count the path to our script and the desired shortcut. As you can see in the following image, I use it for example to debug my blog and then to deploy: as beautiful as it may seem and can help us make us more efficient, with two buttons, you’re done, yes can always optimize. Will you say, what else you can do to optimize this? and why? The reason is simple, in order to run it I necessarily need to have my machine available and turned on. So it would be better where you can always use a server or the cloud in order to do everything remotely so that you can have more control and above all not depend on a local machine. Today there are many tools available for us to run scripts or create small web pages or small applications or showcase sites, the free plan of these services, provides many tools including: Hosting space Database space Functions for microservices Container Virtual machines and whoever has more put them There are so many that sometimes we tend not to see them, despite being under our noses. The ones I use most are: Firebase Google Cloud Amazon AWS Google Script The last service unlike the others is not a cloud service but simply an engine of functions that can be scheduled or activated in relation on google service. They are very integrated with our Google account and it will really give great potential to automate: mailing data synchronization document editing calling external API storing data in excel etc etc … it’s bad to say etc etc but really, the list would be too long, it allows you to automate everything which is Google. The other three are the top three best cloud providers. To begin with I recommend using Firebase because it offers so many services and it is simler and with a faster learning line. Conclusions We have to pay more attention to what we all do without thinking on it. If we do something repetitive every day, even if we take very little time to do it, let’s take it into consideration and think about it. After years, repetitive things can become many and we risk saturating all our time by doing only repetitive things. I leave you and greet you with a phrase that has come to me now. It probably doesn’t make sense or maybe it’s already of someone’s but I don’t know. It is better to create a system that solves a problem than to solve the problem itself!

Fast way to secure your Function with Basic Auth

There are many ways to secure our functions. This topic is not clear when you start using the Cloud Function and it is also constantly changing. I decided to implement my own method that uses the basic and simplest authentication, the Basic Auth. It certainly is not the safest method but it was enough for my purpose. The only flaw is that the function has to be added and implemented in every Cloud function that we make.This implementation then gives us the possibility to call our function from anywhere we want to by simply adding as a parameter of the request the user and the password encrypted in the Basic Auth. To simplify the verification, I created a function that I place in each Cloud Function. This function does the parsing of the request data, verifies if there is a basic auth and, if present, it checks whether the user and password data match. Here is the code I used: var compare = require('tsscmp') const checkAuth = async() => { // parse login and password from headers const b64auth = (req.headers.authorization || '').split(' ')[1] || '' const strauth = new Buffer(b64auth, 'base64').toString() const splitIndex = strauth.indexOf(':') const login = strauth.substring(0, splitIndex) const password = strauth.substring(splitIndex + 1) //function to validate credentials using https://www.npmjs.com/package/tsscmp //Prevents timing attacks using Brad Hill's Double HMAC pattern to perform secure string comparison function check (name, pass) { var valid = true // Simple method to prevent short-circut and use timing-safe compare valid = compare(name, 'user') && valid valid = compare(pass,'password') && valid return valid } if (!check(login, password)) { res.statusCode = 401 res.setHeader('WWW-Authenticate', 'Basic realm="example"') res.end('Access denied') } } Then we can use the function within the method called by our Cloud Function in the following way: exports.helloWorld = async (req, res) => { await checkAuth(); let message = req.query.message || req.body.message || 'Hello World!'; res.status(200).send(message); }; And that’s it, our functions are now safe! Not much but it’s a starting point. So in the end if our system is breached,it is not a big problem, in this function we only return Hello World! How do we instead call our function with Flutter? We simply have to create the Basic Auth with user and password and add it to the request as follows: var basicAuth = 'Basic '+base64Encode(utf8.encode(user:password')); http.Response response = await http.get(apiUrl, headers: <String, String>{'authorization': basicAuth}); print(response.statusCode); //200 print(response.body ); //Hello world! This method is not one of the best, however, it is very fast to implement and also gives us an advantage because it can be used in the same way from all Cloud providers. Finally, we can recall it from anywhere using any language, and it does not force us to use json keys that could be displayed. The only problem I had was having the username and password inside the code that I didn’t really like. I solved it by putting these parameters within the firebase configurations. If you are interested in this, you can read this article Flutter 2 indispensable plugins with great potential.

Metti al sicuro la tua funzione Cloud con Basic Auth

Ci sono tanti modi per poter mettere al sicuro le funzioni. Questo argomento non è chiarissimo dal primo momento in cui si utilizzano le funzioni in Cloud ed è inoltre in continuo cambiamento. Io ho deciso di implementare un mio metodo che utilizza la blasonata e più semplice autenticazione: la Basic Auth. Sicuramente non è la più sicura ma bastava al mio scopo. Unica pecca è che la funzione deve essere aggiunta e implementata in ogni funzione Cloud che andiamo a creare. In questo modo, possiamo chiamare la funzione implementata da dove vogliamo semplicemente aggiungendo come parametro della request user e password criptati nella Basic Auth. Per semplificare la verifica, ho creato, una funzione che inserisco all’interno di ogni Cloud Function. Questa funzione si occupa di fare il parsing dei dati della request, verificare se presente una basic auth e se presente verifica se i dati di user e password corrispondono. Di seguito il codice utilizzato: var compare = require('tsscmp') const checkAuth = async() => { // parse login and password from headers const b64auth = (req.headers.authorization || '').split(' ')[1] || '' const strauth = new Buffer(b64auth, 'base64').toString() const splitIndex = strauth.indexOf(':') const login = strauth.substring(0, splitIndex) const password = strauth.substring(splitIndex + 1) //function to validate credentials using https://www.npmjs.com/package/tsscmp //Prevents timing attacks using Brad Hill's Double HMAC pattern to perform secure string comparison function check (name, pass) { var valid = true // Simple method to prevent short-circut and use timing-safe compare valid = compare(name, 'user') && valid valid = compare(pass,'password') && valid return valid } if (!check(login, password)) { res.statusCode = 401 res.setHeader('WWW-Authenticate', 'Basic realm="example"') res.end('Access denied') } } Successivamente possiamo utilizzare la funzione all’interno del metodo chiamato della nostra Cloud Function nel seguente modo: exports.helloWorld = async (req, res) => { await checkAuth(); let message = req.query.message || req.body.message || 'Hello World!'; res.status(200).send(message); }; Ed il gioco è fatto, le nostre funzioni adesso sono al sicuro. Mica tanto! ma è un inizio. Tanto alla fine se dovessero superare la nostra autenticazione, non sarebbe un grosso problema. In questa funzione restituiamo solo Hello World! Come facciamo invece a richiamare la nostra funzione con Flutter? Dobbiamo semplicemente creare la Basic Auth con user e password e aggiungerla alla request come segue: var basicAuth = 'Basic '+base64Encode(utf8.encode(user:password')); http.Response response = await http.get(apiUrl, headers: <String, String>{'authorization': basicAuth}); print(response.statusCode); //200 print(response.body ); //Hello world! Questo metodo non è uno dei migliori però è molto rapido implementarlo e inoltre ci dà un vantaggio perché può essere utilizzato allo stesso modo per tutti i provider cloud. Infine, possiamo richiamarlo dappertutto utilizzando qualsiasi linguaggio, e non costringe a doversi portare dietro chiavi json che potrebbero essere esposte. L’unico problema che ho avuto è stato quello di avere nel codice scolpiti user e password che non trovavo gradevoli. Ho risolto questo problema mettendo questi parametri all’interno delle configurazioni di firebase. Se siete interessati potete leggere questo articolo Flutter 2 plugin indispensabili dalle grandi potenzialità

Flutter classe utilie per shared preferences

Nell’articolo shared preferences in depth, ho spiegato come utilizzare la shared preferences in Flutter. In questo articolo voglio invece mostrarvi una classe che ho ideato per semplificare l’utilizzo. Ho creato questa classe per l’esigenza di dover memorizzare i dati degli utenti. Ad esempio l’ho usata in Send to Kindle per memorizzare una lista di mail. L’ho usata anche per memorizzare la lista dei token e dati d’acquisto dell’utente. In generale questa struttura può essere utilizzata laddove serve lavorare con una lista di stringhe. Nell’articolo precedente, ho già mostrato come fare a memorizzare una lista di stringhe in local cache. Questa classe però rende l’utilizzo ancora più semplici e aggiunge dei metodi che ci permettono di lavorare in maniera più rapida. Come prima cosa, ho creato il metodo per salvare una lista il local cache nel seguente modo: class CashedUserData { static Future<void> _writes = Future.value(); //add list by key reference in local cache static Future<void> addlist(String kPrefKey, List<String> stringList) async{ _writes = _writes.then((void _) => _doAddList(kPrefKey,stringList)); return _writes; } } static Future<void> _doAddList(String kPrefKey, List<String> list) async { List<String> cached = await load(kPrefKey); cached.addAll(list); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } Successivamente ho creato un altro metodo per recuperare la lista, inoltre ho messo qui i controlli del caso se empty o null: static Future<List<String>> load(String kPrefKey) async { return (await SharedPreferences.getInstance()).getStringList(kPrefKey) ?? []; } Man mano che la usavo ho avuto la necessità di dover aggiungere altri metodi. Metodi per: Cancellare la lista. Inserire una stringa per volta. Fare l’override della lista. Verificare se un elemento esiste. Prendere il primo elemento della lista. Salvare un elemento in top alla lista. In questo modo la classe alla fine è diventata così: class CashedUserData { static Future<void> _writes = Future.value(); static Future<void> overrideListData(String kPrefKey, List<String> stringList) async{ _writes = _writes.then((void _) => _doOverrideListData(kPrefKey,stringList)); return _writes; } static Future<void> addlist(String kPrefKey, List<String> stringList) async{ _writes = _writes.then((void _) => _doAddList(kPrefKey,stringList)); return _writes; } static Future<void> save(String kPrefKey, String id) async{ if(await CashedUserData.exist(kPrefKey, id)) return; _writes = _writes.then((void _) => _doSave(kPrefKey,id)); return _writes; } static Future<void> saveAsFirst(String kPrefKey, String id) async{ List<String> actuaList = await load(kPrefKey); if(actuaList!=null && actuaList.length == 0 ) return save(kPrefKey,id); if(actuaList.contains(id)) actuaList.remove(id); if(actuaList.length>1) actuaList.removeAt(0); List<String> newlist = new List(); newlist.add(id); newlist.addAll(actuaList); _writes = _writes.then((void _) => _doOverrideListData(kPrefKey,newlist)); return _writes; } static Future<void> delete(String kPrefKey, String id) { _writes = _writes.then((void _) => _doDelete(kPrefKey,id)); return _writes; } static Future<String> getFirst(String kPrefKey) async { List<String> dataList = (await SharedPreferences.getInstance()).getStringList(kPrefKey); return (dataList!=null && dataList.length>0) ? dataList[0] : ""; } static Future<List<String>> load(String kPrefKey) async { return (await SharedPreferences.getInstance()).getStringList(kPrefKey) ?? []; } static Future<bool> exist(String kPrefKey, String id) async { List<String> userDataList = (await SharedPreferences.getInstance()).getStringList(kPrefKey) ?? []; return (userDataList!=null && userDataList.length > 0) ? userDataList.contains(id) : false; } static Future<void> _doSave(String kPrefKey, String id) async { List<String> cached = await load(kPrefKey); cached.add(id); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } static Future<void> _doDelete(String kPrefKey, String id) async { List<String> cached = await load(kPrefKey); cached.remove(id); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } static Future<void> _doAddList(String kPrefKey, List<String> list) async { List<String> cached = await load(kPrefKey); cached.addAll(list); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } static Future<void> _doOverrideListData(String kPrefKey, List<String> list) async { await (await SharedPreferences.getInstance()).setStringList(kPrefKey, list); } static update(String kPrefKey, String currentItem, String kindlemail) async{ List<String> actuaList = await load(kPrefKey); if(actuaList!=null && actuaList.length > 0 ) { try{actuaList[actuaList.indexOf(currentItem)] = kindlemail;} catch (e) {} } await overrideListData(kPrefKey, actuaList); } } Facendo così ho semplificato molto e reso più semplice i punti di chiamata. Inoltre se dovesse cambiare il plugin shared preference utilizzato, c’è un unico posto dove dover intervenire.

Flutter useful class for shared preferences

In the article shared preferences in depth, I explained how to use shared preferences in Flutter. In this article I want to show you a class that I designed to simplify its use. I created this class out of the need to store user data. For example, I used it in Send to Kindle to store a mail list. I also used it to store the user’s token list and to purchase data. Overall, this structure can be used where there is the need of working with a list of strings. In my previous article, I have already shown how to store a list of strings in local cache. This class, however, makes it even easier to use and adds methods that allow us to work faster. First, I created the method to save a local cache list as follows: class CashedUserData { static Future<void> _writes = Future.value(); //add list by key reference in local cache static Future<void> addlist(String kPrefKey, List<String> stringList) async{ _writes = _writes.then((void _) => _doAddList(kPrefKey,stringList)); return _writes; } } static Future<void> _doAddList(String kPrefKey, List<String> list) async { List<String> cached = await load(kPrefKey); cached.addAll(list); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } Then I created another method to retrieve the list, I have also put the appropriate checks here, if empty or null: static Future<List<String>> load(String kPrefKey) async { return (await SharedPreferences.getInstance()).getStringList(kPrefKey) ?? []; } As I used it, I needed to add more methods. Methods to: Clear the list. Enter one string at a time Override the list Check if an element exists Take the first item on the list. Save an item at the top of the list. In this way the class eventually became like this: class CashedUserData { static Future<void> _writes = Future.value(); static Future<void> overrideListData(String kPrefKey, List<String> stringList) async{ _writes = _writes.then((void _) => _doOverrideListData(kPrefKey,stringList)); return _writes; } static Future<void> addlist(String kPrefKey, List<String> stringList) async{ _writes = _writes.then((void _) => _doAddList(kPrefKey,stringList)); return _writes; } static Future<void> save(String kPrefKey, String id) async{ if(await CashedUserData.exist(kPrefKey, id)) return; _writes = _writes.then((void _) => _doSave(kPrefKey,id)); return _writes; } static Future<void> saveAsFirst(String kPrefKey, String id) async{ List<String> actuaList = await load(kPrefKey); if(actuaList!=null && actuaList.length == 0 ) return save(kPrefKey,id); if(actuaList.contains(id)) actuaList.remove(id); if(actuaList.length>1) actuaList.removeAt(0); List<String> newlist = new List(); newlist.add(id); newlist.addAll(actuaList); _writes = _writes.then((void _) => _doOverrideListData(kPrefKey,newlist)); return _writes; } static Future<void> delete(String kPrefKey, String id) { _writes = _writes.then((void _) => _doDelete(kPrefKey,id)); return _writes; } static Future<String> getFirst(String kPrefKey) async { List<String> dataList = (await SharedPreferences.getInstance()).getStringList(kPrefKey); return (dataList!=null && dataList.length>0) ? dataList[0] : ""; } static Future<List<String>> load(String kPrefKey) async { return (await SharedPreferences.getInstance()).getStringList(kPrefKey) ?? []; } static Future<bool> exist(String kPrefKey, String id) async { List<String> userDataList = (await SharedPreferences.getInstance()).getStringList(kPrefKey) ?? []; return (userDataList!=null && userDataList.length > 0) ? userDataList.contains(id) : false; } static Future<void> _doSave(String kPrefKey, String id) async { List<String> cached = await load(kPrefKey); cached.add(id); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } static Future<void> _doDelete(String kPrefKey, String id) async { List<String> cached = await load(kPrefKey); cached.remove(id); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } static Future<void> _doAddList(String kPrefKey, List<String> list) async { List<String> cached = await load(kPrefKey); cached.addAll(list); await (await SharedPreferences.getInstance()).setStringList(kPrefKey, cached); } static Future<void> _doOverrideListData(String kPrefKey, List<String> list) async { await (await SharedPreferences.getInstance()).setStringList(kPrefKey, list); } static update(String kPrefKey, String currentItem, String kindlemail) async{ List<String> actuaList = await load(kPrefKey); if(actuaList!=null && actuaList.length > 0 ) { try{actuaList[actuaList.indexOf(currentItem)] = kindlemail;} catch (e) {} } await overrideListData(kPrefKey, actuaList); } } By doing this I simplified the call points. Furthermore, if the plugin shared preference used changed, there would only be one place where to take action.

Quando Flutter incontra DialogFlow nasce un ChatBot multi piattaforma

In questi giorni ho voluto sperimentare e approfondire le conoscenze in ambito di chatbot, ho fatto questa scelta perchè, in questo momento, questa tecnologia è molto utilizzata e molto in crescita. Un pò di teoria I chatbot esistono da tempo, davvero da tanto tempo, risalgono ai primi anni 60/70 con ELIZA e PARRY. Questi due progetti sono nati con lo scopo di creare una conversazione simulata con una macchina. In molti casi, questi due chatbot sono riusciti ad ingannare le persono coinvolte, utilizzando però risposte molto vaghe. Tuttavia, questi due progetti, nonostante fossero classificati come chatbot, risultavano essere molto stupidi, difatto non hanno la stessa concezione del chatbot odierno. Il software che c’era dietro ai vecchi chatbot era molto semplice, possiamo vederlo come una mappatura uno a uno ( domanda -> risposta). Non era presente alcuna interpretazione della domanda. La maggior parte dei Chatbot moderni invece utilizzano il linguaggio naturale che possiamo immaginare con la composizione di tre elementi principali: analisi lessicale (scomposizione frase in token) analisi grammaticale (associazione parti del discorso) analisi sintattica (arrangiamento token in una struttura ad albero) analisi semantica (assegnazione di un significato) Così descritto sembra semplice e noi umani siamo in grado di farlo senza sapere che esistono tutti questi step. Insegnare ad una macchina l’elaborazione degli step sopra elencati è davvero difficile. In particolar modo l’ultimo punto dell’analisi semantica. Oggigiorno I Chatbot più comuni che utilizziamo senza quasi rendercene conto sono Ok Google, Alexa, Siri, Cortona e ogni giorno ne sono presenti sempre di più e di nuovi. Gli ambiti in crescita dove vengono maggiormente utilizzati sono banche, servizio clienti e e-commerce. Ma perchè i chatbot si chiamano con nomi propri di persona? Non ho trovato questa risposta online però credo che la risposta possa essere semplice! Dovendo interagire con qualcosa dalle sembianze umane, quale potrebbe essere il miglior modo per interagire se non quello di attribuire un nome con cui possiamo chiamarlo? Quasi tutte le interazioni con altre persone iniziano con il nome proprio della persona, serve per richiedere la sua attenzione. Cosa c’è dietro al cofano? Ma cosa c’è dietro questi Chatbot? Nel caso di Ok Google, il servizio nelle retroscene è proprio DialogFlow, Questo servizio messo a disposizione di tutti, permette a tutti in modo agile di creare un un vero e proprio chatbot in pochi step e senza alcuna conoscenza di programmazione. Il concetto è molto facile, si basa sulla creazione di Intenti e risposte. Vi spiegherò in questo articolo come utilizzare DialogFlow e come implementarlo usando Flutter. Perchè Flutter? Perchè credo sia molto in crescita al momento. Il progetto sta crescendo così tanto da essere compatibile con tante piattaforme. In particolar modo funziona in maniera nativa su Android e IOS e funziona davvero alla grande. Secondo i test fatti, ha delle prestazioni quasi pari ai linguaggi nativi (Java/Swift/c++). Nonostante sia ancora in Beta, la funzione in modalità web va alla grande e funziona anche per ambienti desktop (linux e Windows). Ma cosa manca? ah già! Tv e Smartwatch! credo però che arriverà a breve anche li il supporto, se ne comincia a parlare online! Mi fai vedere il codice? Non voglio entrare nel dettaglio della configurazione del progetto di dialog flow in quanto ci sono davvero tanti tutorial ben fatti. Do per scontato che abbiate installato Flutter. Se non l’avete ancora fatto, potete partire da questa guida. Dopo aver installato Flutter, visto che la sua concezione è Mobile, se volete compilare anche per web dobbiamo eseguire i seguenti comandi: //abilito la verisone web di flutter flutter channel master flutter upgrade flutter config --enable-web //creo e faccio il run di un nuovo progetto cd into project directory flutter create . flutter run -d chrome Una volta abilitata la versione web di flutter e creato il progetto, possiamo procedere con la modifica del file pubspec.yaml. Questo file contiene le configurazioni e dipendenze ai plugin che utilizziamo nel nostro progetto. Dobbiamo quindi aggiungere le dipendenze a DialogFlow, la versione compatibile sia per web che per mobile è la seguente: flutter_dialogflow: ^0.1.3 assets: - assets/yourapifile.json Dobbiamo anche aggiungere negli asset il file json scaricato da google cloud relativo al service account che ha accesso al progetto di DialogFlow. l’implementazione di dialog Flow richiede davvero poco, giusto qualche riga di codice per l’inizializzazione: dialogFlow.AuthGoogle authGoogle = await dialogFlow.AuthGoogle(fileJson:"assets/yourapifile.json").build(); dialogflow = dialogFlow.Dialogflow(authGoogle: authGoogle); Infine, chiediamo a DialogFlow l’elaborazione dell’intent in modo da ricevere una risposta, con la seguente riga di codice: dialogFlow.AIResponse response = await dialogflow.detectIntent(query); print(response.getMessage()); Potete trovare l’intera implementazione funzionante al seguente link Github. Per poterlo utilizzare, dovrete solo aggiungere la vostra chiave Json del vostro account di servizio, che dovrete creare su google cloud e associare a DialogFlow. schermata del risultato finale:

When Flutter meat DialogFlow born a multi platform ChatBot

In these days, I wanted to experiment and deepen my knowledge in the field of chatbot, I made this choice because at this moment, this technology is widely used and really growing. A little theory Chatbots have been around for a long time, really for a long time, they date back to the early 60s70s with ELIZA and PARRY. These two projects were born for the purpose of creating a simulated conversation with a machine. In many cases, these two chatbots have managed to deceive the people involved, but using very vague but intelligent answers. These two projects, however, despite being classified as chatbots, were very stupid, they do not have the same conception of today’s chatbot. The software behind the old chatbots was very simple, we can see it as a one-to-one mapping (question -> answer). There was no interpretation of the question. Most modern Chatbots, on the other hand, use natural language that we can imagine with the composition of three main elements: lexical analysis (decomposition of sentence into token) grammatical analysis (association of parts of speech) syntactic analysis (token arrangement in a tree structure) analysis semantics (assigning a meaning) Thus described it seems simple and we as humans are able to do it without knowing the existence of all these steps. Teaching a machine how to process the steps listed above is really difficult. Especially the last point of the semantic analysis. Nowadays the most common Chatbots that we use without realizing it are Ok Google, Alexa, Siri, Cortona and every day there are more and more new ones. The growing areas where they are most used are banks, customer service and e-commerce. But why are chatbots called by personal names? I have not found this answer online but I believe the answer is simple. As we have to interact with something with human features, what could be the best way to do it, if not to give a name with which we can call it? Almost all interactions with other people begin with the person’s first name, it is needed to request his/her attention. What’s behind the hood? But what’s behind these Chatbots? In the case of Ok Google, the service in the background is just DialogFlow, This service made available to everyone, allows everyone in an agile way to create a real chatbot in a few steps and without any programming knowledge, the concept is very easy, it is basically based on the creation of intents and answers. I will explain in this article how to use DialogFlow and how to implement it using Flutter. Why Flutter? Because I think it is really growing at the moment. The project is growing so much that it is compatible with many platforms. In particular, it works natively on Android and IOS and works really well, according to the tests made, it has performances almost equal to the native languages ​​(Java / Swift / c ++). Although still in Beta, the Web function is going great, and it also works for desktop environments (linux and Windows). What is missing? Just TV and Smartwatch, I believe that the support will arrive shortly! Can you show me the code? I don’t want to go in detail in DialogFlow configuration, there are really many good tutorials that explain the setup and how to use it. I assume that you have Flutter installed. If you haven’t, you can start from this guide. After installing Flutter, since its conception is Mobile, if you want to compile also for web you must execute the following commands: //enable web flutter versione flutter channel master flutter upgrade flutter config --enable-web //new web project and run in chrome cd into project directory flutter create . flutter run -d chrome Once the web version of flutter has been enabled and the project has been created, we can proceed by update the pubspec.yaml file. This file contains the configurations and dependencies to the plugins that we use in our project. We must therefore add the dependencies to DialogFlow, the compatible version for both web and mobile is as follows: flutter_dialogflow: ^0.1.3 assets: - assets/yourapifile.json We must also add in the assets the json file downloaded from google cloud relating to the service account that has access to the DialogFlow project. The implementation of dialog Flow requires very little, just a few lines of initialization code: dialogFlow.AuthGoogle authGoogle = await dialogFlow.AuthGoogle(fileJson:"assets/yourapifile.json").build(); dialogflow = dialogFlow.Dialogflow(authGoogle: authGoogle); Finally we have to ask DialogFlow to process the intent in order to receive a response, do this with the following line of code: dialogFlow.AIResponse response = await dialogflow.detectIntent(query); print(response.getMessage()); The whole working implementation can be found at the following link Github. In order to use it, you only need to add your service account Json key, which you will have to create on Google Cloud and associate it with DialogFlow. final result screen:

Flutter 2 plugin indispensabili dalle grandi potenzialità

Prerequisiti Questo articolo richiede una discreta conoscenza dei seguenti argomenti che potete approfondire ai seguenti link: Firebase Remote Config Flutter Shared Preferences Come mai vi parlo di questi due plugin che sembrerebbero non avere niente a che fare l’uno con l’altro? Con questa guida, vi illustrerò come trarre beneficio da questi due plugin e come risparmiare usando i servizi gratuiti offerti da Firebase! :) Nell’app Italiano con Eli, creata per il canale Italiano con Eli, ho creato un progetto su Firebase, in modo da poter utilizzare il remote config e altre potenzialità che Firebase mette a disposizione. L’app si occupa di mostrare una lista video da canale youtube, se interessati potete scaricare il codice sorgente su github, potete utilizzarlo con qualsiasi canale youtube. Per rendere l’app Italiano con Eli più originale ho pensato di aggiungere ai video delle domande sugli argomenti trattati nei video. Avevo quindi bisogno di un posto dove salvare i dati delle domande. Con Firebase, la cosa più logica e anche più diretta sarebbe quella di usare Realtime Database oppure Firestore. Io ho pensato di utilizzare remote config! Sì, avete capito bene! Remote config! Il primo pensiero che vi sta saltando in mente in questo momento sarà “questo è pazzo!” e il secondo “ma perchè?” condivido pienamente con voi il vostro primo pensiero… c’è un pò di pazzia nella scelta adottata. Per quanto riguarda il perché invece, posso rispondere come segue: non avevo molto tempo a disposizione remote config è gratis e non ha limitazione di utilizzo si può dare accesso al servizio a una persona esterna le altre scelte mi avrebbero portato a dover costruire anche un’interfaccia back end per il censimento delle domande Conoscevo già remote config e sarei stato più rapido nell’implementazione Ma come funziona un servizio non nato per questo lavoro? Funziona benissimo, devo dire che mi ha sorpreso la reattività che dimostra l’app e il sistema che ho messo in piedi. Per farlo funzionare così bene però ho dovuto mettere assieme i due plugin nel modo che vi spiego di seguito. All’interno della console di remote config vado a inserire un nuovo parametro per ogni video. Nel campo nome inserisco l’id del video di youtube e all’interno del parametro un json contenente le domande e le risposte così strutturato: { "Playlist": "PLsrqydfBIVzy9IMGwSQieTVeSWC7cRCnN", "Questions": [ { "question": "How do you say how much is it??: ", "answare": [ "Quanto costa?", "Quanto costano? ", "Quanto costi?" ] }, { "question": "How do you say how much are they?: ", "answare": [ "Quanto costano?", "Quanto costate?", "entrambe/both" ] }, { "question": "Choose the correct option", "answare": [ "Quanto costa questo computer? 300 Euro", "quanto computer ti costa? 300 Euro", "Quanto costano questo computer?" ] }, { "question": "Quanto costa? is", "answare": [ "singolare", "plurale" ] } ] } Inoltre firebase mette a disposizione un inserimento facilitato che effettua anche la validazione del json, questo ci permette di editare più facilmente e non commettere errori. Nell’app Flutter ho poi costruito l’oggetto Quiz che conterrà l’id di youtube, una lista di Domande e la Domanda conterrà una lista di Risposte. Con vari metodi utili di gestione e costruttore per deserializzazione dei dei dati Json come segue: class Answer { final String answerText; final bool isCorrect; Answer(this.answerText, this.isCorrect); } class Question { final String question; final List<Answer> answers; Question(this.question, this.answers); } class Quiz { List<Question> _questions; int _currentIndex = -1; int _score = 0; String _videoId; Quiz.fromJson(String videoId, String jsonInput){ _videoId = videoId; _questions = new List<Question>(); var jsonQuestions = json.decode(jsonInput); jsonQuestions['Questions'].forEach((quest) { List<Answer> answers = new List<Answer>(); bool iscorrect=true; quest['answare'].forEach((ans) { //mettere la prima a true answers.add( new Answer(ans, iscorrect) ); iscorrect=false; }); answers.shuffle(); _questions.add( new Question( quest['question'], answers) ); }); } Quiz(this._questions) { _questions.shuffle(); } List<Question> get questions => _questions; int get length => _questions.length; int get questionNumber => _currentIndex + 1; int get score => _score; Question get nextQuestion { _currentIndex++; if (_currentIndex >= length) return null; return _questions[_currentIndex]; } Question get prevQuestion { _currentIndex--; if (_currentIndex < 0) return null; return _questions[_currentIndex]; } String get correctAnsware { return _questions[_currentIndex].answers.where((x) => x.isCorrect == true).first.answerText; } void answer(bool isCorrect) { if (isCorrect) _score++; } saveScore() async { SharedPreferences preferences = await SharedPreferences.getInstance(); preferences.setInt("OK"+_videoId, this.score); preferences.setInt("KO"+_videoId, this.length - this.score ); //preferences.setString(_videoId, "{'questions':'"+ this.length.toString() +"', 'score':'"+ this.score.toString() +"'}"); } } Per prima cosa, l’App recupera la lista dei video tramite le API youtube, successivamente recupera il relativo json da remote config utilizzando l’id del video e lo passa al costruttore dell’oggetto che lo deserializza ed il gioco è fatto! Una volta ultimata l’app mi sono accorto però che youtube mette a disposizione un numero limitato di chiamate API giornaliere e oltretutto ho pensato che fosse inutile che l’App, ogni volta che viene aperta, debba richiamare le API Youtube. I video oltretutto non cambiano tanto in quanto questo canale produce un nuovo video a settimana. Per risolvere il problema delle chiamate API Youtube e rendere il tutto più reattivo ho deciso di salvare tutto in una lista di stringhe json in cache utilizzando proprio la Shared Preferences. Infine ho aggiunto un parametro nella remote config contente una data. In questo modo ho fatto un meccanismo che mi permette di aggiornare i contenuti nei dispositivi solo se la data è più recente rispetto a quella memorizzata in cache del singolo dispositivo stesso: class YoutubeData { RemoteConfig remoteConfig; String apikey; List<YoutubeDto> allYoutubeVideoList = []; List<YoutubeDto> getHomeList() { return List<YoutubeDto>.from(allYoutubeVideoList.where((item) => item.kind == "video" && item.id != item.channelId )); } List<YoutubeDto> allCategory() { return List<YoutubeDto>.from(allYoutubeVideoList.where((item) => item.kind == "playlist" && item.id != item.channelId )); } List<YoutubeDto> getCategoryVideoList(String plylistID) { return List<YoutubeDto>.from(allYoutubeVideoList.where((item) => item.kind == "video" && item.id != item.channelId && item.playlist == plylistID )); } YoutubeData (this.apikey, this.remoteConfig); checkAndLoad() async { SharedPreferences preferences = await SharedPreferences.getInstance(); List<String> videoIDList = preferences.getStringList("VideoIdList"); DateTime lastUpdateDate,updateDate; String date = remoteConfig.getString("UpdateDatetime"); updateDate = DateTime.parse(date); if(preferences.getString("LastUpdateDatetime")!=null && preferences.getString("LastUpdateDatetime").isNotEmpty) lastUpdateDate = DateTime.parse(preferences.getString("LastUpdateDatetime")); else lastUpdateDate = DateTime(2010); if( (videoIDList==null || videoIDList.length==0) || updateDate.isAfter(lastUpdateDate)) { await loadYtDataAndStoreInSharedPref(); preferences.setString("LastUpdateDatetime", DateTime.now().toString() ); } await loadLocalDataAndAddQuestion(); } loadYtDataAndStoreInSharedPref() async { YoutubeAPI ytApi = new YoutubeAPI(apikey, maxResults: 50); List<YT_API> ytResult = await ytApi.channel( remoteConfig.getString('ChannelId') ); //salviamo il conteggio dei video in shared pref SharedPreferences preferences = await SharedPreferences.getInstance(); preferences.setInt("TotVideo", ytResult.length ); //salviamo json youtube video in shared pref e lista video YoutubeDto youtubedto = new YoutubeDto(); List<String> videoIdList = new List<String>(); for(var result in ytResult) { videoIdList.add( result.id); String json = jsonEncode( youtubedto.yApitoJson(result) ); preferences.setString( result.id, json ); } preferences.setStringList("VideoIdList", videoIdList ); } //aggiungiamo le domande agli oggetti youtube precedentemente salvati loadLocalDataAndAddQuestion() async { SharedPreferences preferences = await SharedPreferences.getInstance(); List<String> videoIDList = preferences.getStringList("VideoIdList"); allYoutubeVideoList = new List<YoutubeDto>(); int cntQuestion=0; for(String videoID in videoIDList) { String jsonYoutube = preferences.getString(videoID); Map userMap = jsonDecode(jsonYoutube); YoutubeDto youtubeDao = new YoutubeDto.fromJson(userMap); youtubeDao.questionJson = remoteConfig.getString( "_" + videoID.replaceAll("-", "_trattino_") ); if( youtubeDao.questionJson != null && youtubeDao.questionJson.isNotEmpty ) { cntQuestion = cntQuestion + 'question'.allMatches(youtubeDao.questionJson).length; youtubeDao.playlist = json.decode( youtubeDao.questionJson)['Playlist']; } allYoutubeVideoList.add(youtubeDao); } preferences.setInt("TotQuestion", cntQuestion ); } } Qui di seguito potete vedere un esempio di come funziona:

Flutter 2 plugin necessary with great potentiality

Prerequisites This article requires a good knowledge of the following topics that you can study at the following links: Firebase Remote Config Flutter Shared Preferences Why are we talking about these two plugins that would see having nothing in common? i With this guide I will show you how to benefit from this two plugins and how to save money using the free services offered by Firebase! :) In the talian with Eli app, created for the youtube channel Italian with Eli, I created a project on Firebase, so you can use the remote config and other potential that Firebase makes available for you. The app takes care of showing a video list from the youtube channel, if interested you can download the source code on github, you can use it with any youtube channel. To make the Italian with Eli app more original I thought of adding questions to the videos on the topics covered in the videos. So I needed a place to save the question data. With Firebase, the most logical and also most direct thing would be to use Realtime Database or Firestore. I thought of using remote config! Yes you got it right remote config! You will be thinking “this guy is crazy” and “why is he doing that?” I fully share with you this thought… there is a bit of madness in the choice made. The reason why I thought of using remote config is the following: I didn’t have much time available remote config is free and has no limitation of use you can give access to the service to an external person the other choices would have led me to have to also build a back end interface to allow the census of the questions I had already used remote config and I would have been faster in the implementation. But how does a service not born with this scope work? It works very well indeed, I must say that I was surprised by the responsiveness that shows the app and the system that I put up. To make it work so well, however, I had to put the two plugins together in the way that I explain below. Inside the remote config console I’m going to insert a new parameter for each video. In the name field I insert the id of the youtube video and inside the parameter a json containing the questions and answers structured as follows: { "Playlist": "PLsrqydfBIVzy9IMGwSQieTVeSWC7cRCnN", " Questions ": [ { " question ":" How do you say how much is it ??: ", " answare ": [ " How much does it cost? ", " How much does it cost? ", " How much does it cost? " ] }, { "question": "How do you say how much are they ?:", "answare": [ "How much do they cost?", "How much do you cost?", "both / both" ] }, { "question" : "Choose the correct option", "answare": [ "How much does this computer cost? 300 Euros", "How much computer does it cost? 300 Euros", "How much does this computer cost?" ] }, { "question": "How much does it cost? is", "answare": [ "singular", "plural" ] } ] } In addition, firebase provides an easy insertion that also performs json validation, this allows us to edit more easily and not to make mistakes. In the Flutter app I then built the Quiz object which contains the youtube id, a list of Questions and the Question will contain a list of Answers. With various useful management and constructor methods for deserializing Json data as follows: class Answer { final String answerText; final bool isCorrect; Answer (this.answerText, this.isCorrect); } class Question { final String question; final List <Answer> answers; Question (this.question, this.answers); } class Quiz { List <Question> _questions; int _currentIndex = -1; int _score = 0; String _videoId; Quiz.fromJson (String videoId, String jsonInput) { _videoId = videoId; _questions = new List <Question> (); var jsonQuestions = json.decode (jsonInput); jsonQuestions ['Questions']. forEach ((quest) { List <Answer> answers = new List <Answer> (); bool iscorrect = true; quest ['answare']. forEach ((ans) { // put the first to true answers.add (new Answer (ans, iscorrect)); iscorrect = false; }); answers.shuffle (); _questions.add (new Question (quest ['question'], answers)); }); } Quiz (this._questions) { _questions.shuffle (); } List <Question> get questions => _questions; int get length => _questions.length; int get questionNumber => _currentIndex + 1; int get score => _score; Question get nextQuestion { _currentIndex ++; if (_currentIndex> = length) return null; return _questions [_currentIndex]; } Question get prevQuestion { _currentIndex--; if (_currentIndex <0) return null; return _questions [_currentIndex]; } String get correctAnsware { return _questions [_currentIndex] .answers.where ((x) => x.isCorrect == true) .first.answerText; } void answer (bool isCorrect) { if (isCorrect) _score ++; } saveScore () async { SharedPreferences preferences = await SharedPreferences.getInstance (); preferences.setInt ("OK" + _ videoId, this.score); preferences.setInt ("KO" + _ videoId, this.length - this.score); //preferences.setString(_videoId, "{'questions': '" + this.length.toString () + "', 'score': '" + this.score.toString () + "'}"); } } The app first retrieves the list of videos via the youtube API, then retrieves the relative json from remote config using the video id and passes it to the constructor of the object that deserialize and you’re done. Once the app was completed, however, I realized that youtube provides a limited number of daily API calls. Moreover I thought it was useless every time I opened the app that it had to call the Youtube API. The videos, moreover, do not change as much as the channel makes a new video a week. To solve the problem of Youtube API calls and make everything more responsive, I decided to save everything in a list of cached json strings using the Shared Preferences. Finally I added a parameter in the remote config containing a date. In this way I made a mechanism that allows me to update the contents on the devices only if the date is more recent than the one stored in the cache of the single device itself: class YoutubeData { RemoteConfig remoteConfig; String apikey; List <YoutubeDto> allYoutubeVideoList = []; List <YoutubeDto> getHomeList () { return List <YoutubeDto> .from (allYoutubeVideoList.where ((item) => item.kind == "video" && item.id! = Item.channelId)); } List <YoutubeDto> allCategory () { return List <YoutubeDto> .from (allYoutubeVideoList.where ((item) => item.kind == "playlist" && item.id! = Item.channelId)); } List <YoutubeDto> getCategoryVideoList (String plylistID) { return List <YoutubeDto> .from (allYoutubeVideoList.where ((item) => item.kind == "video" && item.id! = Item.channelId && item.playlist == plylistID)); } YoutubeData (this.apikey, this.remoteConfig); checkAndLoad () async { SharedPreferences preferences = await SharedPreferences.getInstance (); List <String> videoIDList = preferences.getStringList ("VideoIdList"); DateTime lastUpdateDate, updateDate; String date = remoteConfig.getString ("UpdateDatetime"); updateDate = DateTime.parse (date); if (preferences.getString ("LastUpdateDatetime")! = null && preferences.getString ("LastUpdateDatetime"). isNotEmpty) lastUpdateDate = DateTime.parse (preferences.getString ("LastUpdateDatetime")); else lastUpdateDate = DateTime (2010); if ((videoIDList == null || videoIDList.length == 0) || updateDate.isAfter (lastUpdateDate)) { await loadYtDataAndStoreInSharedPref (); preferences.setString ("LastUpdateDatetime", DateTime.now (). toString ()); } await loadLocalDataAndAddQuestion (); } loadYtDataAndStoreInSharedPref () async { YoutubeAPI ytApi = new YoutubeAPI (apikey, maxResults: 50); List <YT_API> ytResult = await ytApi.channel (remoteConfig.getString ('ChannelId')); // save the video count in shared pref SharedPreferences preferences = await SharedPreferences.getInstance (); preferences.setInt ("TotVideo", ytResult.length); // save json youtube video in shared pref andvideo list YoutubeDtoyoutubedto = new YoutubeDto (); List <String> videoIdList = new List <String> (); for (var result in ytResult) { videoIdList.add (result.id); String json = jsonEncode (youtubedto.yApitoJson (result)); preferences.setString (result.id, json); } preferences.setStringList ("VideoIdList", videoIdList); } // add the questions to the previously saved youtube objects loadLocalDataAndAddQuestion () async { SharedPreferences preferences = await SharedPreferences.getInstance (); List <String> videoIDList = preferences.getStringList ("VideoIdList"); allYoutubeVideoList = new List <YoutubeDto> (); int cntQuestion = 0; for (String videoID in videoIDList) { String jsonYoutube = preferences.getString (videoID); Map userMap = jsonDecode (jsonYoutube); YoutubeDto youtubeDao = new YoutubeDto.fromJson (userMap); youtubeDao.questionJson = remoteConfig.getString ("_" + videoID.replaceAll ("-", "_trattino_")); if (youtubeDao.questionJson! = null && youtubeDao.questionJson.isNotEmpty) { cntQuestion = cntQuestion + 'question'.allMatches (youtubeDao.questionJson) .length; youtubeDao.playlist = json.decode (youtubeDao.questionJson) ['Playlist']; } allYoutubeVideoList.add (youtubeDao); } preferences.setInt ("TotQuestion", cntQuestion); } } Below you can see an example of how it works:

Che cos'è Firebase Remote Config

Il nome scelto da Google questa volta è molto comprensivo ed esaustivo. Firebase remote config è una configurazione salvata in remoto, in questo caso su Google Cloud. La configurazione è accessibile in modifica nella console di Firebase, alla voce di menù Firebase remote config che si trova in fondo, molto in fondo, nell’ultima sezione secondo me un pò nascosta. Prerequisiti: creare un account su Firebase utilizzando il nostro account google creare un app, io ho usato flutter collegare la nostra app al codice sorgente con la chiave json Facendo questo potremmo utilizzare tutti i servizi Firebase, ci sono tanti tutorial online e Firebase stesso mette a disposizione wizard con step per guidarvi alla corretta implementazione di Firebase con la vostra app.Possiamo usare Firebase Remote Config per memorizzare tutto quello che la nostra app necessità come parametri di configurazioni. Per prima cosa, dobbiamo individuare e mettere in configurazione ciò che pensiamo possa cambiare nel tempo, in questo modo avremo delle configurazioni nell’app modificabili in tempo reale da remoto in modo da non dover rieffettuare un nuovo deploy dell’app stessa. Un esempio può essere il caso in cui stiamo utilizzando un Api per recuperare dei dati, l’url base delle api potrebbe cambiare nel tempo. Un altro esempio più concreto che utilizzo io nell’app send to kindle è un parametro che contiene il numero di azioni prima di mostrare una pubblicità. In questo modo se gli utenti si lamentano per le troppe pubblicità posso cambiarlo in tempo reale con il solo cambio di un parametro da interfaccia web a costo zero. Il sistema di Firebase funziona davvero alla grande, c’è dietro un sistema push-lazy che utilizza i dati internet per recuperare le configurazioni solo se davvero abbiamo cambiato qualcosa lato server e quindi abbiamo pubblicato una modifica ad uno o più parametri. L’aggiornamento dei parametri avviene in real time e quindi la modifica sarà subito disponibile nell’app. I parametri possono essere anche associati a delle condizioni. Ad esempio un parametro può essere utilizzato solo per gli utenti di una certa età di un determinato paese o lingua a un determinato orario. Figata no? Vantaggi Controllo da remoto istantaneo, semplice e centralizzato. Modifica App in tempo reale. Diminuisce la necessità di dover effettuare un nuovo deploy. i parametri possono essere combinati con delle condizioni. Come lo uso io nelle mie app? Di seguito voglio mostrarvi un esempio di implementazione. In questo modo ho centralizzato la parte di inizializzazione e creazione dei parametri in modo che siano più accessibili. Ho deciso di utilizzare un singleton in modo da poterlo usare in tutte le view e in tutte le classi per cui ne ho bisogno, implementato nel seguente modo: import 'package:firebase_remote_config/firebase_remote_config.dart'; class Configuration { int _link_sent_before_ads; int _max_send_limit_size = 24000000; int get linkSentBeforeAds => _link_sent_before_ads; int get maxSendLimitSize => _max_send_limit_size; int get maxSendLimitSizeMb => (_max_send_limit_size/1000000).round(); static Configuration get instance => _instance; static final Configuration _instance = Configuration._privateConstructor(); Configuration._privateConstructor() { //initializeRemoteConfig(); } loadConfig(RemoteConfig _remoteConfig) async { _link_sent_before_ads = _remoteConfig.getString('link_sent_before_ads').isEmpty ? _link_sent_before_ads : int.tryParse(_remoteConfig.getString('link_sent_before_ads')); _max_send_limit_size = _remoteConfig.getString('max_send_limit_size').isEmpty ? _max_send_limit_size : int.tryParse(_remoteConfig.getString('max_send_limit_size')); } initializeRemoteConfig() async{ RemoteConfig remoteConfig = await RemoteConfig.instance; try { //set some default params in case of crash await remoteConfig.setConfigSettings(RemoteConfigSettings(debugMode: false)); await remoteConfig.setDefaults(<String, dynamic>{ 'service_api_conversion_1': 'https://ebook-converter.app/calibre/ebook-convert', }); // Using default duration to force fetching from remote server. await remoteConfig.fetch(expiration: const Duration(seconds: 0)); await remoteConfig.activateFetched(); } on FetchThrottledException catch (exception) { // Fetch throttled. print(exception); } catch (exception) { print('Unable to fetch remote config. Cached or default values will be used'); } await this.loadConfig(remoteConfig); } } potrà essere infine utilizzato molto semplicemente nel seguente modo: //call this just first time in app initialization await Configuration.instance.initializeRemoteConfig(); Print(Configuration.instance.maxSendLimitSize);

Flutter Shared Preferences in depth

What is shared_preferences where, when and how much to use it? The shared_preference is a plugin that allows you to save data app dedicated memory, the folder that will contain this data is named in Android with the package name of your app, e.g. com.companyname.appname. The data that we can store in this space with this plugin are data of these types: String Integer Bool List It should be noted that these parameters are not persistent, they remain in the area dedicated to the app therefore are eliminated when the app is uninstalled or if the app cache data is removed. So, in general it is right to store non-essential preference data so that it is not a tragedy if they have been lost. A classic example can be the app theme color light or dark or the order of menu title. How to use? Saving: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); _preferences.setString("theme", "dark"); _preferences.setInt("countaccess", 2); Recovery: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); _preferences.getString("theme"); _preferences.getInt("countaccess"); At first we might think that it is of little use since in a string we cannot store a lot of information. In fact, if we think about it in a string, we can also store a lot but really a lot by using a json, below an example: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); _preferences.setString("{"name":"Andrea","surname":"Luciano","age":31,"sex":"M","SurnameCouldBeName":true}"); In this example I put SurnameCouldBeName as a field because my last name is also a first name. All those who don’t know me always ask me “Luciano is your name or surname?” And every time I would like to do something like that: We can therefore create a collection of people using a list of strings instead of the single string as follows: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); List<String> users = new List<String>(); users.add("{"name":"Andrea","surname":"Luciano","age":31,"sex":"M","SurnameCouldBeName":true}"); users.add("{"name":"elisa","surname":"luciano","age":32,"sex":"F","SurnameCouldBeName":false}"); _preferences.setStringList("users", users); This could finally be mapped into an object in order to access the data simply and finally show it to the interface: Class UserDto() { String name, surname, age, sex, SurnameCouldBeName; UserDto.fromJson(Map<String, dynamic> json) : name= json[name], surname= json[surname], age= json[age], sex= json[sex], SurnameCouldBeName = json[SurnameCouldBeName]; } SharedPreferences _preferences = await SharedPreferences.getInstance(); List<UserDto> UserObj = new List<UserDto>; List<String> users = _preferences.getStringList("users"); for(String userjson in users) { Map userMap = jsonDecode(userjson); UserDto = new UserDto.fromJson(userMap); print(UserDto.name); UserObj.add(UserDto); } Think about the possible benefits and applications of this. It can be used to store data returned by an API. In this way, the application would be more efficient and also can work offline without therefore having to use network data for recovering data from the server.

Flutter Shared Preferences in profondità

Che cos’è la shared_preferences dove, quando e quanto utilizzarla? La shared_preference è un plugin che vi permette di salvare dei dati in memoria dedicata all’app, la cartella che li conterrà prende il nome in android con il nome del pacchetto della vostra app es com.nomeazienda.nomeapp. I dati che possiamo memorizzare all’interno di questa memoria con questo plugin sono dei seguenti tipi: string intero bool List E’ da notare che questi parametri non sono persistenti, rimangono nell’area dedicata all’app e quindi vengono eliminate nel momento in cui l’app viene disinstallata oppure se vengono rimossi i dati della cache dell’app. Quindi in genere è doveroso memorizzare dati di preferenze non indispensabili in modo che non sia una tragedia se dovessero essere persi. Un esempio classico può essere come voglio il tema light o dark oppure l’ordine degli oggetti nel menu. Come si usa? Salvataggio: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); _preferences.setString("theme", "dark"); _preferences.setInt("countaccess", 2); Recupero: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); _preferences.getString("theme"); _preferences.getInt("countaccess"); In un primo momento potremmo pensare che è una cosa che serve a poco in quanto in una stringa non possiamo memorizzare tante informazioni. In realtà, se ci pensiamo bene, in una stringa possiamo anche memorizzare molto ma davvero molto semplicemente utilizzando un json, di seguito esempio: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); _preferences.setString("{"name":"Andrea","surname":"Luciano","age":31,"sex":"M","SurnameCouldBeName":true}"); In questo esempio ho messo come campo SurnameCouldBeName in quanto il mio cognome è anche un nome. Tutti quelli che non mi conoscono mi chiedono sempre “Luciano è il nome o il cognome?” E ogni volta vorrei fare qualcosa del genere: Possiamo quindi creare una collezione di persone utilizzando, al posto della singola stringa, una lista di stringhe come segue: import 'package:shared_preferences/shared_preferences.dart'; SharedPreferences _preferences = await SharedPreferences.getInstance(); List<String> users = new List<String>(); users.add("{"name":"Andrea","surname":"Luciano","age":31,"sex":"M","SurnameCouldBeName":true}"); users.add("{"name":"elisa","surname":"luciano","age":32,"sex":"F","SurnameCouldBeName":false}"); _preferences.setStringList("users", users); Questo infine potrebbe essere mappato in un oggetto in modo da accedere ai dati più semplicemente ed infine mostrarli nell’interfaccia: Class UserDto() { String name, surname, age, sex, SurnameCouldBeName; UserDto.fromJson(Map<String, dynamic> json) : name= json[name], surname= json[surname], age= json[age], sex= json[sex], SurnameCouldBeName = json[SurnameCouldBeName]; } SharedPreferences _preferences = await SharedPreferences.getInstance(); List<UserDto> UserObj = new List<UserDto>; List<String> users = _preferences.getStringList("users"); for(String userjson in users) { Map userMap = jsonDecode(userjson); UserDto = new UserDto.fromJson(userMap); print(UserDto.name); UserObj.add(UserDto); } Pensate ai possibili vantaggi e alle possibili applicazioni. Può essere utilizzato per memorizzare dati restituiti da un API. Con questo approccio, l’applicazione è più efficiente e potrebbe funzionare anche offline senza quindi dover utilizzare sempre la rete dati per recuperare i dati dal server.

What is Firebase Remote Config

The name chosen by Google this time is very comprehensive and exhaustive. Firebase remote config is a remotely saved configuration, in this case on Google Cloud. This configuration is accessible to insert and update in the Firebase console, under the menu item Firebase remote config which is located at the very bottom, in the last section, in my opinion a little hidden. Prerequisites: create an account on Firebase using our google account create an app, I used flutter connect our app to the source code using json key file By doing this we could use all the Firebase services, there are many online tutorials and Firebase itself provides wizards with steps to guide you to the correct implementation of Firebase with your app. We can use Firebase Remote Config to store everything our app needs as configuration parameters. First of all, We must identify and configure what we think will change over time. In this way we will have configurations in the app that can be modified in real time remotely so as not to have to carry out a new app deployment. An example may be the case in which we are using an API to recover data, the base url may change over time. Another more down to earth-example that I use in the send to kindle app is a parameter that contains the number of actions before showing an advertisement. In this way, if users complain about too many advertisements, I can change it in real time with just changing a parameter into the web interface at no cost. The Firebase system works really well, there is a push-lazy system behind it that uses internet data to retrieve the configurations only if we have really changed something on the server side and therefore we have published a change to one or more parameters. The updating of the parameters takes place in real time so it changes immediately the behavior, state or data in app as real time. Parameters can also be associated with conditions. For example, a parameter can only be used for users of a certain age in a certain country or language at a specific time. Cool! isn’t it? Advantages Instant and simple remote control. Real-time app customization. It decreases the need for a new deployment. Parameters can be combined with conditions. How do I use it in my apps? Below I want to show you an example of implementation. In this way I centralized the initialisation and parameter creation part so that they are more accessible. I decided to use a singleton so that I can use it in all the views and all the classes I need it, implemented in the following way: import 'package:firebase_remote_config/firebase_remote_config.dart'; class Configuration { int _link_sent_before_ads; int _max_send_limit_size = 24000000; int get linkSentBeforeAds => _link_sent_before_ads; int get maxSendLimitSize => _max_send_limit_size; int get maxSendLimitSizeMb => (_max_send_limit_size/1000000).round(); static Configuration get instance => _instance; static final Configuration _instance = Configuration._privateConstructor(); Configuration._privateConstructor() { //initializeRemoteConfig(); } loadConfig(RemoteConfig _remoteConfig) async { _link_sent_before_ads = _remoteConfig.getString('link_sent_before_ads').isEmpty ? _link_sent_before_ads : int.tryParse(_remoteConfig.getString('link_sent_before_ads')); _max_send_limit_size = _remoteConfig.getString('max_send_limit_size').isEmpty ? _max_send_limit_size : int.tryParse(_remoteConfig.getString('max_send_limit_size')); } initializeRemoteConfig() async{ RemoteConfig remoteConfig = await RemoteConfig.instance; try { //set some default params in case of crash await remoteConfig.setConfigSettings(RemoteConfigSettings(debugMode: false)); await remoteConfig.setDefaults(<String, dynamic>{ 'service_api_conversion_1': 'https://ebook-converter.app/calibre/ebook-convert', }); // Using default duration to force fetching from remote server. await remoteConfig.fetch(expiration: const Duration(seconds: 0)); await remoteConfig.activateFetched(); } on FetchThrottledException catch (exception) { // Fetch throttled. print(exception); } catch (exception) { print('Unable to fetch remote config. Cached or default values will be used'); } await this.loadConfig(remoteConfig); } } It can finally be used very simply in the following way: //call this just first time in app initialization await Configuration.instance.initializeRemoteConfig(); Print(Configuration.instance.maxSendLimitSize);

Flutter everithings is a widget! Why? But Really!

Theory Flutter is a new language that has recently come out from the beta, implemented by Google on the basis of Dartlanguage less known today than FLutter. It is a modern language but based on Dart, the syntax is very similar to any other modern object language. The main concept on which it is based is Everything is a widget. But what does it really mean? All we are dealing with when developing in Flutter is a widget. A widget may or may not have a status, which can determine its content or form. It could be seen as an object as you imagine it with the difference that it can have a state to update the view and it can contain contents and shapes. Yes, you have understood shapes correctly, since a widget, besides defining properties and methods, can define shapes. Finally, a widget can include or extend another widget. So an app in flutter is the composition of the widgets together. An example could be a form containing n input text widgets etc. and a button also widget. The main widget that we can make are of two types, at least for now before google upsets everything, and are as follows: Widgets stateless (statelesswidget) are immutable, like a static class. A button that never changes color can be defined as a static widget. It can also be used in case we need to show only non-interactive descriptions. Stateful widgets (statefulwidget): one (or more) property related to them, changing, can change the behavior, appearance or functionality of the widget. An app screen that changes based on content in an http response is a widget with status (just because the screen content varies based on the http response). Example: in case we need to request data from users and then update the same widget to validate or show an ok data entered correctly. To update the widget you need to use the setstate with the property updated so that the change is extended. Consideration The thing I liked most about Flutter: that we can develop everything through a single language. the livereload works really well and allows us to write the code faster. with single environment and same code we have a build for Android and IOS as Native Recently flutter can also be used in web and desktop (Linux & Windows) :) At the beginning I was a little skeptical about using widgets and it was a little complicated and dispersed to understand the advantages. After using them I must say that they are simpler than they seem to be implemented and thanks to this approach it will be easier to reason according to the best practice “DRY” (Don’t Repeat Yourself). On the one hand it adds an incredible nesting during the construction phase of the interface by boxing one widget into another and so on; however it has a logic that is modular in nature and this is excellent for decoupling small widgets that will consist of their properties and their tasks. By decoupling, we can test them and use them with different widgets to make more complex widgets. In this way the code will be more maintainable and functional.

Flutter tutto è un widget! Perchè? Ma veramente?

Teoria Flutter è un nuovo linguaggio uscito da non molto dalla beta, implementato da google sulla base del linguaggio Dart, meno noto ad oggi di FLutter. E’ un linguaggio moderno ma basandosi su Dart, la sintassi è molto simile a qualsiasi altro linguaggio moderno ad oggetti. Il concetto principale su cui si basa è Everything is a widget. Ma cosa vuol dire davvero? Tutto ciò con cui abbiamo a che fare sviluppando in Flutter è un widget. Un widget può avere o meno uno stato, che ne può determinare contenuto o forma. Potrebbe essere visto come un oggetto come lo immaginate con la differenza che può avere uno stato per aggiornare la view e può contenere contenuti e forme. Sì, avete capito bene! forme in quanto un widget oltre a definire proprietà e metodi, può definire forme. Infine un widget può includere o estendere un altro widget. Quindi un’applicazione in flutter è la composizione dei widget insieme. Un esempio può essere un form che contiene un widget di input text ecc. e un botton anch’esso widget. I widget principali che possiamo realizzare sono di due tipi, almeno per adesso prima che google sconvolga tutto, e sono i seguenti: Widget privi di stato (statelesswidget): sono immutabili, come una classe statico. Un bottone che non cambia mai colore può essere definito come uno widget statico, può essere utilizzato anche nel caso abbiamo bisogno di mostrare solo descrizioni non interattive. Widget dotati di stato (statefulwidget): una (o più) proprietà ad essi afferente, cambiando, può mutare il comportamento, le sembianze o le funzionalità del widget. Una schermata dell’app che cambia in base al contenuto in una risposta http è un widget dotato di stato (proprio perché il contenuto della schermata varia in base alla risposta http). Esempio: nel caso in cui dobbiamo richiedere dei dati agli utenti e poi riaggiornare lo stesso widget per validare o mostrare un ok dati inseriti correttamente. Per aggiornare il widget è necessario utilizzare il setstate con la proprietà aggiornata in modo che venga prorogata la modifica. Considerazioni La cosa che ho apprezzato di più di Flutter: che possiamo sviluppare tutto tramite un unico linguaggio. il live reload funziona davvero bene e ci permette di scrivere il codice più velocemente. Dobbiamo scrivere e manutenere un’ unica linea di codice fruibile su Android e IOS come nativo. da poco con la stessa linea di codice è possibile fare il build anche per web e desktop (Linux e Windows) :) All’inizio ero un pò scettico nell’utilizzare i widget ed è stato un pò complicato e dispersivo comprenderne i vantaggi. Tuttavia, dopo averli utilizzati devo dire che sono più semplici di quello che sembrano da implementare e grazie a questo approccio sarà più semplice ragionare secondo la best practice “DRY” (Don’t Repeat Yourself). Da un lato aggiunge una nidificazione incredibile in fase di costruzione dell’interfaccia iscatolando un widget dentro un altro e così via, dall’altro ha una logica che di sua natura è modulare e ciò è ottimo per disaccoppiare piccoli widget che saranno consistenti delle loro proprietà e i loro compiti. Disaccoppiando, possiamo testarli e usarli con diversi widget per fare widget più complessi. In questo modo il codice sarà più manutenibile e funzionale.

Come creare un Blog con Hugo e Google Docs come BackEnd

Ricerca Eccoci qua finalmente! In questi giorni ho sentito la necessità di creare questo blog che state proprio visitando! Mentre navigavo on line, sono venuto a conoscenza degli static site generator; ho sempre saputo della loro esistenza ma non avevo mai dedicato loro molta importanza. Tuttavia, navigando più a fondo, sono stato attratto da Hugo, uno fra i tanti nuovi motori per generare website statici. No Wordpres Partivo dall’esigenza di avere qualcosa di statico in quanto non dispongo di un server dove installare Wordpress o altri CMS e, per un piccolo blog personale, non credo sia necessario e oltretutto è troppo costoso. Infine, volevo che il blog fosse efficiente e scalabile e cross platform. DRY La prima cosa a cui ho pensato da programmatore è stata: quante operazioni dovrò fare per eseguire un deploy senza un CMS? come farò a portare i miei nuovi contenuti online? Sono anche un’amante di Google Docs e mi piace scrivere ed avere tutto in un unico posto. Allora mi sono chiesto: come posso unire Hugo e Google Docs senza dover girare mille manovelle? Innanzitutto, ho studiato la struttura dei contenuti MarkDown e mi sono messo alla ricerca di qualcosa che mi desse la possibilità di convertire i Documenti Google in MarkDown. La cosa più utile che ho trovato sul web è stato questo Google script mangini/gdocs2md: Convert a Google Drive Document to the Markdown format, suitable for publishing. a cui faccio i miei più sentiti ringraziamenti. Nonostante la comprovata efficacia del suddetto script, avevo bisogno di qualcosa in più rispetto al ricevere la conversione di un articolo via mail. Di conseguenza, per avere qualcosa di più automatizzato, ho modificato un pò lo script e creato il link che vedi sotto: Link allo script su github Lo script converte tutti i documenti elencati in un foglio Google, organizza in cartelle per categorie, estrae immagini da articoli, aggiunge l’intestazione del MarkDown, i tags ed infine crea un file zip contenente tutti i contenuti. Ho deciso di impostare lo zip con visibilità pubblica quindi scaricabile, pronto per il deploy. Ho successivamente creato una sorta di database utilizzando uno sheet di Google come se fosse una tabella con la seguente struttura: ToDeploy Title Summary SummaryImage Category Data tag1 tag2 tag3 tag4 tag5 Language 1 Come Inviare File PDF e articoli web al Kindle da Android 0 Kindle 2020-05-09 kindle pdf articolo web send to kindle android it In questo modo ho la possibilità di fare il deploy di tutto o di aggiornare solo ciò che ho modificato utilizzando il primo campo ToDeploy. Successivamente, ho creato un altro google script che riceve in ingresso l’id della cartella su cui è presente lo zip precedentemente creato e restituisce l’url pubblico da cui effettuare il download dello zip con i contenuti. function doGet(e) { params = JSON.parse(JSON.stringify(e)); var docid = params.parameters.docid; if(docid==null || docid=="") return; var parentFolder=DriveApp.getFolderById(docid); if(parentFolder==null) return; var url = parentFolder.getFilesByName("BlogProd.zip").next().getDownloadUrl(); return ContentService.createTextOutput(url); } Infine ho messo tutte insieme all’interno del seguente script linux sh in modo da poter automatizzare build e il deploy: #!/bin/bash #ln -s /home/yourname/works/luciosoftsite/blog/ ~/luciosoftsite #ln -s /home/yourname/works/luciosoftsite/blog/content/ ~/luciosoftblogcontent #requirements wget|unzip|hugo folderid="your google doc folder id” yourscriptid=”your google script id” cd ~/luciosoftblogcontent; retriveurl="https://script.google.com/macros/s/$scriptid/exec?folderid=$folderid”; downlodUrl=$(wget $retriveurl -q -O -); fileName="download.zip"; wget -c $downlodUrl -O $fileName; unzip -o $fileName; rm -f $fileName; cd ~/luciosoftblog; #hugo serve -D HUGO_ENV="production" hugo --config config.yaml firebase deploy Lo script è molto semplice, non fa altro che richiamare lo script google per recuperare l’url di download. Una volta recuperato l’url, a questo punto lo script effettua il download dello zip, estrae i contenuti all’interno del folder dei contenuti di Hugo, esegue il comando per creare Build, ed infine richiama firebase per effettuare il deploy. E anche oggi la magia è avvenuta. Sì, probabilmente avrei potuto seguire mille altre strade, anche più sicure e più efficienti ma questo è un inizio, il mio obiettivo era più grande. Vorrei trasformare lo script linux in un container docker e lo script google in un’applicazione dinamica con login google. Ma questa è un’altra storia che, se avrà seguito, vedrete prossimamente in un altro link all’interno del mio blog :) Poject ghithub link

How to create a Blog with Hugo e Google Docs as BackEnd

Research In these days I have felt the need to create the blog you are reading. While surfing the web, I became aware of the static site generators, I have always known what they are and that they have always existed but I had never given them much attention. Though, while surfing deeper, I was attracted by Hugo, one of the many new engines to generate static websites. No WordPress I needed to have something static for I don’t have a server where I can install Wordpress or other CMS and, for a small personal blog, I don’t think it’s necessary and it is also too expensive. Finally I wanted the blog to be efficient and scalable and cross platform. DRY The first thing I thought about as a programmer was: how many operations do I need to do to deploy without a CMS? how will I bring my new content online? I am also a Google Docs lover and I like writing and having everything in one place. So I asked to myself: how do I combine Hugo and Google Docs without having to turn a thousand cranks? I studied the structure of MarkDown content and I started looking for something to convert Google Docs to MarkDown. The only useful thing I found on the web was this Googlescript mangini/ gdocs2md: Convert to Google Drive Document to the Markdown format, suitable for publishing. to whom I offer my heartfelt thanks. Although this script is very effective, I needed something more than receiving the conversion of an article by email. To have something more automated, I modified the script a bit and created the link script as follows: Link to my github repos The script converts all the documents listed in a Google sheet, organizes into folders by categories, extracts images from articles, adds the MarkDown header, tags and finally creates a zip file containing all the contents. I decided to make the zip public and therefore downloadable, ready for deployment. I then created a sort of database using a Google sheet as a table with this struct: ToDeploy Title Summary SummaryImage Category Date tag1 tag2 tag3 Tag4 Tag5 Language 1 Send As PDF files and web articles to the Kindle from Android 0 Kindle 09/05/2020 kindle pdf web article send to kindle android it In this way I have the possibility to deploy everything or to update only what I modified using the first field ToDeploy field. Subsequently, I created another google script that receives the id of the folder where there is the previously created zip. The script finally returns the public url from which it is possible to download the zip with the contents. function doGet (e) { params = JSON.parse (JSON.stringify (e)); var docid = params.parameters.docid; if (docid == null || docid == "") return; var parentFolder = DriveApp.getFolderById (docid); if (parentFolder == null) return; var url = parentFolder.getFilesByName ("BlogProd.zip"). next (). getDownloadUrl (); return ContentService.createTextOutput (url); } Finally I put them all together in the following script linux sh. So I can automate building and deployment: #!/bin/bash #ln -s /home/yourname/works/luciosoftsite/blog/ ~/luciosoftsite #ln -s /home/yourname/works/luciosoftsite/blog/content/ ~/luciosoftblogcontent #requirements wget|unzip|hugo folderid=”your google doc folder id” yourscriptid=”your google script id” cd ~/luciosoftblogcontent; retriveurl="https://script.google.com/macros/s/$scriptid/exec?folderid=$folderid”; downlodUrl=$(wget $retriveurl -q -O -); fileName="download.zip"; wget -c $downlodUrl -O $fileName; unzip -o $fileName; rm -f $fileName; cd ~/luciosoftblog; #hugo serve -D HUGO_ENV="production" hugo --config config.yaml firebase deploy The script is very simple, it calls the google script to retrieve the download url. Once the url is recovered, the script does the download of the zip, extracts the contents into the Hugo contents folder, executes the command to create Build, and finally calls firebase for deploy. And even today the magic has happened. Yes, I could have followed a thousand other ways, even safer and more efficient. But this is a starting point, my goal is bigger. I would like to turn the linux script into a docker container and the google script into a dynamic application with google login. But this is another story that, maybe, you will be able to see in another link at my blog :) Link al progetto ghithub