1660885920
Criar um novo projeto Flutter é uma bênção - base de código nova, nenhum código legado (ainda), segurança nula, versões mais recentes de seus pacotes favoritos e assim por diante. Mas, ao mesmo tempo, você deve tomar decisões críticas no início do projeto que estabeleceriam as bases para o futuro, como ferramentas, pacotes, estrutura de arquivos, solução de gerenciamento de estado, plano de teste. Caso contrário, o projeto acabaria se transformando em apenas mais uma tigela de espaguete e almôndegas. Para evitar isso, preparei uma lista, na minha opinião, dos elementos mais importantes do projeto que devem ser decididos logo no início. Espero que ajude você, portanto - boa leitura!
1. Análise de código estático
Eu não vou escrever código confuso ( fonte )
O Linter é uma ferramenta de análise estática que identifica e sinaliza erros de programação, avisos, falhas de estilo em seu código para você corrigi-los. No contexto do Flutter, essa é uma das coisas mais fáceis de implementar e uma das mais úteis para manter seu código limpo.
Existem várias regras diferentes que você pode definir para o seu código seguir, mas eu recomendaria usar um dos conjuntos predefinidos que já seguem as melhores práticas com base no Dart Style Guide :
Qualquer que seja o pacote escolhido, você sempre pode adicionar ou remover qualquer regra de análise estática específica no arquivo analysis_options.yaml .
2. Localização (l10n)
Localização ( fonte )
O que é localização ( l10n , em suma)?
Localização é a adaptação de um produto ou serviço para atender às necessidades de uma determinada língua, cultura ou “look-and-feel” de uma população desejada. — Tech Target
É essencial construir um aplicativo que pareça natural para os usuários, por exemplo, usando as traduções corretas, formatos de data e moeda, direção do texto. Para isso, a localização é uma ferramenta fundamental a ser utilizada. Mesmo que você esteja criando um único aplicativo de região/idioma, eu ainda recomendo que você implemente a localização desde o início, separando assim seus textos do código da interface do usuário. Consequentemente, eles podem ser reutilizados e ajustados posteriormente sem afetar o código.
A documentação do Flutter explica perfeitamente o processo de internacionalização do seu aplicativo. Se a maneira padrão parecer muito complexa e/ou você precisar de algumas extensões e métodos auxiliares úteis, existem pacotes populares de terceiros, como easy_localization , que podem ajudá-lo no processo de localização.
3. Ambientes (com alguns sabores)
Ambientes de programação ( fonte )
Aposto que você já ouviu pelo menos um caso do seu ambiente (sem trocadilhos) quando alguém corrompeu dados ou excluiu toda a tabela de usuários em produção. Confie em mim - isso não é divertido. Portanto, é uma boa prática criar ambientes diferentes para o seu projeto:
Ter esses ambientes ajuda você a experimentar e verificar recursos com segurança antes que essas alterações cheguem às mãos dos usuários.
Agora, outra parte – sabores . Não, não, não estamos falando de algo doce, salgado ou azedo - esse é apenas mais um termo usado em programação para descrever diferentes variantes de compilação para seu aplicativo. Por exemplo, você deseja que o ícone e o título, o endpoint da API ou qualquer outra configuração sejam diferentes para cada ambiente específico. Para isso, você define um “sabor” diferente que é usado quando o aplicativo está sendo construído para um ambiente específico. Aqui estão alguns recursos sobre como criar sabores para o Flutter .
4. Integração Contínua e Entrega Contínua (CI/CD)
Etapas de Integração Contínua (CI) e Entrega Contínua (CD) ( fonte )
Após a introdução de diferentes ambientes, o próximo passo natural é automatizar o processo de construção, teste e liberação de seu aplicativo. CI/CD é um tópico bastante complexo por si só e eu não sou um especialista neste campo de forma alguma, portanto, eu recomendaria procurar alguns outros recursos sobre como automatizar diferentes estágios de desenvolvimento de aplicativos.
No entanto, existem muitas soluções NoOps compatíveis com o Flutter para que você possa automatizar seu processo de desenvolvimento com facilidade:
Qualquer uma dessas soluções faria o truque - basta selecionar aquela que se adapta às suas necessidades e orçamento.
5. Código de back-end
Uma vez outro meme sobre backend ( source )
Você já tem seu backend implementado em alguma linguagem de programação exótica ou talvez não tão sofisticada? Ótimo, você pode pular esta etapa, mas eu ainda recomendaria verificar algumas soluções em nuvem para referência futura.
Na versão simplificada, há duas opções para a parte de back-end do seu aplicativo:
Caso a segunda opção pareça atraente para você, existem algumas ótimas plataformas de nuvem para escolher com suporte ao Flutter:
As plataformas de nuvem fornecem autenticação, banco de dados, armazenamento, opções de API para seu aplicativo e muitos outros recursos. Qualquer uma dessas é uma ótima opção quando você só precisa validar a ideia e construir o MVP rapidamente sem gastar muito tempo na solução de back-end completa.
6. Registro, dados de falhas e análises
Ops, algo deu errado ( fonte )
O registro é subestimado – aqui, eu disse isso! Tudo está legal até que algo dê errado e você precise de informações sobre isso. Há sempre uma área cinzenta quando discutimos o que deve ser registrado e o que não deve ser registrado. Mas uma coisa é sempre clara - você deve saber quando seu aplicativo falha e o que causa o problema. Quanto mais dados você coletar sobre o incidente, mais fácil será encontrar e corrigir o problema.
Serviços como Sentry , Firebase Crashlytics , Datadog podem ajudá-lo a registrar os dados mais importantes, relatórios de falhas ou até mesmo configurar notificações quando seu aplicativo ou serviços relacionados estiverem inativos.
Outro tipo de registro é a coleta de dados do usuário para fins de análise. Quando você está construindo um produto novo, talvez único, é crucial entender as necessidades de seus usuários, seu comportamento e como eles estão usando o aplicativo. Para isso, várias ferramentas de análise podem ser integradas ao seu aplicativo Flutter, como Firebase Analytics , App Center Analytics e muito mais.
7. Marca do aplicativo
Tema do material ( fonte )
Um dos principais objetivos de qualquer aplicativo ou marca é ser reconhecível. Usar a paleta de cores, o logotipo, os ícones, os elementos de design, o conteúdo, a fonte e às vezes até o layout corretos faz com que seu produto se destaque dos demais. Isso é a marca do aplicativo , e preparar as partes fundamentais no início economizará muito tempo durante todo o projeto.
Se você já tem seu protótipo de interface do usuário ou componentes de design prontos, agora é um bom momento para transferi-los para seu aplicativo e definir temas - cores, fontes, formas, etc. Para facilitar, Mike Rydstrom criou um pacote excelente para este — flex_color_scheme .
8. Estrutura do projeto e gestão do estado
Gerenciamento de estado no Flutter ( fonte )
Sim, o polêmico. Só para deixar claro, não existe “a melhor solução de gerenciamento de estado” ou “a melhor arquitetura do aplicativo” – se alguém disser o contrário, lembre-se de que provavelmente também despeja o leite na tigela antes do cereal. E essa é a pior parte - eu não posso te ensinar a melhor maneira. Só posso fornecer várias opções ou compartilhar minhas preferências.
Várias opções de estrutura de arquivos para o próximo projeto Flutter:
Sobre a gestão estadual em Flutter – acho que estamos no ponto em que poderíamos dedicar toda a conferência a esse tópico e ainda não ter uma resposta final depois. Apenas para adicionar meus dois centavos, escolha aquele com o qual você se sente mais confortável. Você pode encontrar uma lista abrangente de opções aqui .
9. Geração de código
Geração de código ( fonte )
Se você quiser cortar alguns cantos e economizar algum tempo de desenvolvimento, você pode usar a geração de código em seu projeto. Codifique menos, entregue mais !
Há uma variedade de ferramentas diferentes para usar, seja trabalhando com localizações, ativos, analisando JSON, gerando classes de modelo, implementando localizador de serviço, roteamento ou trabalhando com estados imutáveis. A única coisa a fazer é investigar as ferramentas e pacotes disponíveis e escolher os melhores para cobrir as necessidades do seu projeto.
Para um início rápido do projeto Flutter, eu recomendaria verificar o Very Good CLI . Isso economizaria várias horas de configuração (infelizmente, aprendi da maneira mais difícil).
Além disso, no mês passado eu dei uma palestra sobre geração de código - pode ser um ponto de partida para sua jornada de geração de código Flutter, então confira!
10. Estratégia de teste
Teste de aplicativos ( fonte )
É bom ou ruim cobrir 100% do seu código com testes? Claro, é incrível, mas a que custo? Pensando dessa forma, você pode cair no poço condenado onde você gasta mais tempo escrevendo testes do que desenvolvendo recursos. Para evitar isso, você precisa de uma estratégia de teste.
Não me entenda mal — cobrir seu código com testes é ótimo e quanto mais lugares obscuros do seu código forem cobertos, mais seguro você se sentirá ao implementar novos recursos. Apenas, na minha opinião, você deve encontrar o equilíbrio onde os testes ainda trazem mais valor em comparação com o tempo gasto em escrevê-los. Por exemplo, esta é a minha estratégia de teste:
Honestamente, ainda estou procurando essa média de ouro nos testes, mas você fica melhor nisso projeto após projeto, confie em mim.
11. Arquivo LEIA-ME
Faça um README ( fonte )
Você me ouviu direito - documentação. O arquivo README é o documento mais importante do projeto, principalmente quando se trabalha em equipe.
Você acabou de introduzir uma nova solução que requer geração de código? Você acabou de adicionar um novo script bash útil para automatizar o processo? Você implementou um registrador global que DEVE ser usado em todos os lugares do projeto? Não podemos ler sua mente - mencione isso no arquivo README!
Não existe muita documentação (pelo menos eu não estive em tal situação), apenas a falta de informações sobre o projeto e o código. Todos os comandos para gerar, testar e executar o código, várias decisões de estrutura de arquivos, diagramas, ferramentas e serviços externos, informações sobre diferentes ambientes (SEM CHAVES SECRETAS) devem ser colocados aqui e mantidos em um único local. Este é um trabalho chato, mas muito gratificante!
Ufa, que passeio… ( fonte )
É isso! Obrigado pelo seu tempo lendo este artigo.
Perdi alguma coisa? Mencione isso nos comentários! Qual é a sua lista de verificação ao criar um novo aplicativo Flutter?
1659817260
The AWS IoT Device SDK for Embedded C (C-SDK) is a collection of C source files under the MIT open source license that can be used in embedded applications to securely connect IoT devices to AWS IoT Core. It contains MQTT client, HTTP client, JSON Parser, AWS IoT Device Shadow, AWS IoT Jobs, and AWS IoT Device Defender libraries. This SDK is distributed in source form, and can be built into customer firmware along with application code, other libraries and an operating system (OS) of your choice. These libraries are only dependent on standard C libraries, so they can be ported to various OS's - from embedded Real Time Operating Systems (RTOS) to Linux/Mac/Windows. You can find sample usage of C-SDK libraries on POSIX systems using OpenSSL (e.g. Linux demos in this repository), and on FreeRTOS using mbedTLS (e.g. FreeRTOS demos in FreeRTOS repository).
For the latest release of C-SDK, please see the section for Releases and Documentation.
C-SDK includes libraries that are part of the FreeRTOS 202012.01 LTS release. Learn more about the FreeRTOS 202012.01 LTS libraries by clicking here.
The C-SDK libraries are licensed under the MIT open source license.
C-SDK simplifies access to various AWS IoT services. C-SDK has been tested to work with AWS IoT Core and an open source MQTT broker to ensure interoperability. The AWS IoT Device Shadow, AWS IoT Jobs, and AWS IoT Device Defender libraries are flexible to work with any MQTT client and JSON parser. The MQTT client and JSON parser libraries are offered as choices without being tightly coupled with the rest of the SDK. C-SDK contains the following libraries:
The coreMQTT library provides the ability to establish an MQTT connection with a broker over a customer-implemented transport layer, which can either be a secure channel like a TLS session (mutually authenticated or server-only authentication) or a non-secure channel like a plaintext TCP connection. This MQTT connection can be used for performing publish operations to MQTT topics and subscribing to MQTT topics. The library provides a mechanism to register customer-defined callbacks for receiving incoming PUBLISH, acknowledgement and keep-alive response events from the broker. The library has been refactored for memory optimization and is compliant with the MQTT 3.1.1 standard. It has no dependencies on any additional libraries other than the standard C library, a customer-implemented network transport interface, and optionally a customer-implemented platform time function. The refactored design embraces different use-cases, ranging from resource-constrained platforms using only QoS 0 MQTT PUBLISH messages to resource-rich platforms using QoS 2 MQTT PUBLISH over TLS connections.
See memory requirements for the latest release here.
The coreHTTP library provides the ability to establish an HTTP connection with a server over a customer-implemented transport layer, which can either be a secure channel like a TLS session (mutually authenticated or server-only authentication) or a non-secure channel like a plaintext TCP connection. The HTTP connection can be used to make "GET" (include range requests), "PUT", "POST" and "HEAD" requests. The library provides a mechanism to register a customer-defined callback for receiving parsed header fields in an HTTP response. The library has been refactored for memory optimization, and is a client implementation of a subset of the HTTP/1.1 standard.
See memory requirements for the latest release here.
The coreJSON library is a JSON parser that strictly enforces the ECMA-404 JSON standard. It provides a function to validate a JSON document, and a function to search for a key and return its value. A search can descend into nested structures using a compound query key. A JSON document validation also checks for illegal UTF8 encodings and illegal Unicode escape sequences.
See memory requirements for the latest release here.
The corePKCS11 library is an implementation of the PKCS #11 interface (API) that makes it easier to develop applications that rely on cryptographic operations. Only a subset of the PKCS #11 v2.4 standard has been implemented, with a focus on operations involving asymmetric keys, random number generation, and hashing.
The Cryptoki or PKCS #11 standard defines a platform-independent API to manage and use cryptographic tokens. The name, "PKCS #11", is used interchangeably to refer to the API itself and the standard which defines it.
The PKCS #11 API is useful for writing software without taking a dependency on any particular implementation or hardware. By writing against the PKCS #11 standard interface, code can be used interchangeably with multiple algorithms, implementations and hardware.
Generally vendors for secure cryptoprocessors such as Trusted Platform Module (TPM), Hardware Security Module (HSM), Secure Element, or any other type of secure hardware enclave, distribute a PKCS #11 implementation with the hardware. The purpose of corePKCS11 mock is therefore to provide a PKCS #11 implementation that allows for rapid prototyping and development before switching to a cryptoprocessor specific PKCS #11 implementation in production devices.
Since the PKCS #11 interface is defined as part of the PKCS #11 specification replacing corePKCS11 with another implementation should require little porting effort, as the interface will not change. The system tests distributed in corePKCS11 repository can be leveraged to verify the behavior of a different implementation is similar to corePKCS11.
See memory requirements for the latest release here.
The AWS IoT Device Shadow library enables you to store and retrieve the current state one or more shadows of every registered device. A device’s shadow is a persistent, virtual representation of your device that you can interact with from AWS IoT Core even if the device is offline. The device state is captured in its "shadow" is represented as a JSON document. The device can send commands over MQTT to get, update and delete its latest state as well as receive notifications over MQTT about changes in its state. The device’s shadow(s) are uniquely identified by the name of the corresponding "thing", a representation of a specific device or logical entity on the AWS Cloud. See Managing Devices with AWS IoT for more information on IoT "thing". This library supports named shadows, a feature of the AWS IoT Device Shadow service that allows you to create multiple shadows for a single IoT device. More details about AWS IoT Device Shadow can be found in AWS IoT documentation.
The AWS IoT Device Shadow library has no dependencies on additional libraries other than the standard C library. It also doesn’t have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any JSON library (see demos with coreMQTT and coreJSON).
See memory requirements for the latest release here.
The AWS IoT Jobs library enables you to interact with the AWS IoT Jobs service which notifies one or more connected devices of a pending “Job”. A Job can be used to manage your fleet of devices, update firmware and security certificates on your devices, or perform administrative tasks such as restarting devices and performing diagnostics. For documentation of the service, please see the AWS IoT Developer Guide. Interactions with the Jobs service use the MQTT protocol. This library provides an API to compose and recognize the MQTT topic strings used by the Jobs service.
The AWS IoT Jobs library has no dependencies on additional libraries other than the standard C library. It also doesn’t have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any JSON library (see demos with libmosquitto and coreJSON).
See memory requirements for the latest release here.
The AWS IoT Device Defender library enables you to interact with the AWS IoT Device Defender service to continuously monitor security metrics from devices for deviations from what you have defined as appropriate behavior for each device. If something doesn’t look right, AWS IoT Device Defender sends out an alert so you can take action to remediate the issue. More details about Device Defender can be found in AWS IoT Device Defender documentation. This library supports custom metrics, a feature that helps you monitor operational health metrics that are unique to your fleet or use case. For example, you can define a new metric to monitor the memory usage or CPU usage on your devices.
The AWS IoT Device Defender library has no dependencies on additional libraries other than the standard C library. It also doesn’t have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any JSON library (see demos with coreMQTT and coreJSON).
See memory requirements for the latest release here.
The AWS IoT Over-the-air Update (OTA) library enables you to manage the notification of a newly available update, download the update, and perform cryptographic verification of the firmware update. Using the OTA library, you can logically separate firmware updates from the application running on your devices. You can also use the library to send other files (e.g. images, certificates) to one or more devices registered with AWS IoT. More details about OTA library can be found in AWS IoT Over-the-air Update documentation.
The AWS IoT Over-the-air Update library has a dependency on coreJSON for parsing of JSON job document and tinyCBOR for decoding encoded data streams, other than the standard C library. It can be used with any MQTT library, HTTP library, and operating system (e.g. Linux, FreeRTOS) (see demos with coreMQTT and coreHTTP over Linux).
See memory requirements for the latest release here.
The AWS IoT Fleet Provisioning library enables you to interact with the AWS IoT Fleet Provisioning MQTT APIs in order to provison IoT devices without preexisting device certificates. With AWS IoT Fleet Provisioning, devices can securely receive unique device certificates from AWS IoT when they connect for the first time. For an overview of all provisioning options offered by AWS IoT, see device provisioning documentation. For details about Fleet Provisioning, refer to the AWS IoT Fleet Provisioning documentation.
See memory requirements for the latest release here.
The AWS SigV4 library enables you to sign HTTP requests with Signature Version 4 Signing Process. Signature Version 4 (SigV4) is the process to add authentication information to HTTP requests to AWS services. For security, most requests to AWS must be signed with an access key. The access key consists of an access key ID and secret access key.
See memory requirements for the latest release here.
The backoffAlgorithm library is a utility library to calculate backoff period using an exponential backoff with jitter algorithm for retrying network operations (like failed network connection with server). This library uses the "Full Jitter" strategy for the exponential backoff with jitter algorithm. More information about the algorithm can be seen in the Exponential Backoff and Jitter AWS blog.
Exponential backoff with jitter is typically used when retrying a failed connection or network request to the server. An exponential backoff with jitter helps to mitigate the failed network operations with servers, that are caused due to network congestion or high load on the server, by spreading out retry requests across multiple devices attempting network operations. Besides, in an environment with poor connectivity, a client can get disconnected at any time. A backoff strategy helps the client to conserve battery by not repeatedly attempting reconnections when they are unlikely to succeed.
The backoffAlgorithm library has no dependencies on libraries other than the standard C library.
See memory requirements for the latest release here.
When establishing a connection with AWS IoT, users can optionally report the Operating System, Hardware Platform and MQTT client version information of their device to AWS. This information can help AWS IoT provide faster issue resolution and technical support. If users want to report this information, they can send a specially formatted string (see below) in the username field of the MQTT CONNECT packet.
Format
The format of the username string with metrics is:
<Actual_Username>?SDK=<OS_Name>&Version=<OS_Version>&Platform=<Hardware_Platform>&MQTTLib=<MQTT_Library_name>@<MQTT_Library_version>
Where
Example
/* Username string:
* iotuser?SDK=Ubuntu&Version=20.10&Platform=RaspberryPi&MQTTLib=coremqtt@1.1.0
*/
#define OS_NAME "Ubuntu"
#define OS_VERSION "20.10"
#define HARDWARE_PLATFORM_NAME "RaspberryPi"
#define MQTT_LIB "coremqtt@1.1.0"
#define USERNAME_STRING "iotuser?SDK=" OS_NAME "&Version=" OS_VERSION "&Platform=" HARDWARE_PLATFORM_NAME "&MQTTLib=" MQTT_LIB
#define USERNAME_STRING_LENGTH ( ( uint16_t ) ( sizeof( USERNAME_STRING ) - 1 ) )
MQTTConnectInfo_t connectInfo;
connectInfo.pUserName = USERNAME_STRING;
connectInfo.userNameLength = USERNAME_STRING_LENGTH;
mqttStatus = MQTT_Connect( pMqttContext, &connectInfo, NULL, CONNACK_RECV_TIMEOUT_MS, pSessionPresent );
C-SDK releases will now follow a date based versioning scheme with the format YYYYMM.NN, where:
For example, a second release in June 2021 would be 202106.01. Although the SDK releases have moved to date-based versioning, each library within the SDK will still retain semantic versioning. In semantic versioning, the version number itself (X.Y.Z) indicates whether the release is a major, minor, or point release. You can use the semantic version of a library to assess the scope and impact of a new release on your application.
All of the released versions of the C-SDK libraries are available as git tags. For example, the last release of the v3 SDK version is available at tag 3.1.2.
API documentation of 202108.00 release
This release introduces the refactored AWS IoT Fleet Provisioning library and the new AWS SigV4 library.
Additionally, this release brings minor version updates in the AWS IoT Over-the-Air Update and corePKCS11 libraries.
API documentation of 202103.00 release
This release includes a major update to the APIs of the AWS IoT Over-the-air Update library.
Additionally, AWS IoT Device Shadow library introduces a minor update by adding support for named shadow, a feature of the AWS IoT Device Shadow service that allows you to create multiple shadows for a single IoT device. AWS IoT Jobs library introduces a minor update by introducing macros for $next
job ID and compile-time generation of topic strings. AWS IoT Device Defender library introduces a minor update that adds macros to API for custom metrics feature of AWS IoT Device Defender service.
corePKCS11 also introduces a patch update by removing the pkcs11configPAL_DESTROY_SUPPORTED
config and mbedTLS platform abstraction layer of DestroyObject
. Lastly, no code changes are introduced for backoffAlgorithm, coreHTTP, coreMQTT, and coreJSON; however, patch updates are made to improve documentation and CI.
API documentation of 202012.01 release
This release includes AWS IoT Over-the-air Update(Release Candidate), backoffAlgorithm, and PKCS #11 libraries. Additionally, there is a major update to the coreJSON and coreHTTP APIs. All libraries continue to undergo code quality checks (e.g. MISRA-C compliance), and Coverity static analysis. In addition, all libraries except AWS IoT Over-the-air Update and backoffAlgorithm undergo validation of memory safety with the C Bounded Model Checker (CBMC) automated reasoning tool.
API documentation of 202011.00 release
This release includes refactored HTTP client, AWS IoT Device Defender, and AWS IoT Jobs libraries. Additionally, there is a major update to the coreJSON API. All libraries continue to undergo code quality checks (e.g. MISRA-C compliance), Coverity static analysis, and validation of memory safety with the C Bounded Model Checker (CBMC) automated reasoning tool.
API documentation of 202009.00 release
This release includes refactored MQTT, JSON Parser, and AWS IoT Device Shadow libraries for optimized memory usage and modularity. These libraries are included in the SDK via Git submoduling. These libraries have gone through code quality checks including verification that no function has a GNU Complexity score over 8, and checks against deviations from mandatory rules in the MISRA coding standard. Deviations from the MISRA C:2012 guidelines are documented under MISRA Deviations. These libraries have also undergone both static code analysis from Coverity static analysis, and validation of memory safety and data structure invariance through the CBMC automated reasoning tool.
If you are upgrading from v3.x API of the C-SDK to the 202009.00 release, please refer to Migration guide from v3.1.2 to 202009.00 and newer releases. If you are using the C-SDK v4_beta_deprecated branch, note that we will continue to maintain this branch for critical bug fixes and security patches but will not add new features to it. See the C-SDK v4_beta_deprecated branch README for additional details.
Details available here.
All libraries depend on the ISO C90 standard library and additionally on the stdint.h
library for fixed-width integers, including uint8_t
, int8_t
, uint16_t
, uint32_t
and int32_t
, and constant macros like UINT16_MAX
. If your platform does not support the stdint.h
library, definitions of the mentioned fixed-width integer types will be required for porting any C-SDK library to your platform.
Guide for porting coreMQTT library to your platform is available here.
Guide for porting coreHTTP library is available here.
Guide for porting AWS IoT Device Shadow library is available here.
Guide for porting AWS IoT Device Defender library is available here.
Guide for porting OTA library to your platform is available here.
Migration guide for MQTT library is available here.
Migration guide for Shadow library is available here.
Migration guide for Jobs library is available here.
The main branch hosts the continuous development of the AWS IoT Embedded C SDK (C-SDK) libraries. Please be aware that the development at the tip of the main branch is continuously in progress, and may have bugs. Consider using the tagged releases of the C-SDK for production ready software.
The v4_beta_deprecated branch contains a beta version of the C-SDK libraries, which is now deprecated. This branch was earlier named as v4_beta, and was renamed to v4_beta_deprecated. The libraries in this branch will not be released. However, critical bugs will be fixed and tested. No new features will be added to this branch.
This repository uses Git Submodules to bring in the C-SDK libraries (eg, MQTT ) and third-party dependencies (eg, mbedtls for POSIX platform transport layer). Note: If you download the ZIP file provided by GitHub UI, you will not get the contents of the submodules (The ZIP file is also not a valid git repository). If you download from the 202012.00 Release Page page, you will get the entire repository (including the submodules) in the ZIP file, aws-iot-device-sdk-embedded-c-202012.00.zip. To clone the latest commit to main branch using HTTPS:
git clone --recurse-submodules https://github.com/aws/aws-iot-device-sdk-embedded-C.git
Using SSH:
git clone --recurse-submodules git@github.com:aws/aws-iot-device-sdk-embedded-C.git
If you have downloaded the repo without using the --recurse-submodules
argument, you need to run:
git submodule update --init --recursive
When building with CMake, submodules are also recursively cloned automatically. However, -DBUILD_CLONE_SUBMODULES=0
can be passed as a CMake flag to disable this functionality. This is useful when you'd like to build CMake while using a different commit from a submodule.
The libraries in this SDK are not dependent on any operating system. However, the demos for the libraries in this SDK are built and tested on a Linux platform. The demos build with CMake, a cross-platform build tool.
stdint.h
is required for fixed-width integer types that include uint8_t
, int8_t
, uint16_t
, uint32_t
and int32_t
, and constant macros like UINT16_MAX
, while stdbool.h
is required for boolean parameters in coreMQTT. For compilers that do not provide these header files, coreMQTT provides the files stdint.readme and stdbool.readme, which can be renamed to stdint.h
and stdbool.h
, respectively, to provide the required type definitions.Build Dependencies
The follow table shows libraries that need to be installed in your system to run certain demos. If a dependency is not installed and cannot be built from source, demos that require that dependency will be excluded from the default all
target.
Dependency | Version | Usage |
---|---|---|
OpenSSL | 1.1.0 or later | All TLS demos and tests with the exception of PKCS11 |
Mosquitto Client | 1.4.10 or later | AWS IoT Jobs Mosquitto demo |
You need to setup an AWS account and access the AWS IoT console for running the AWS IoT Device Shadow library, AWS IoT Device Defender library, AWS IoT Jobs library, AWS IoT OTA library and coreHTTP S3 download demos. Also, the AWS account can be used for running the MQTT mutual auth demo against AWS IoT broker. Note that running the AWS IoT Device Defender, AWS IoT Jobs and AWS IoT Device Shadow library demos require the setup of a Thing resource for the device running the demo. Follow the links to:
The MQTT Mutual Authentication and AWS IoT Shadow demos include example AWS IoT policy documents to run each respective demo with AWS IoT. You may use the MQTT Mutual auth and Shadow example policies by replacing [AWS_REGION]
and [AWS_ACCOUNT_ID]
with the strings of your region and account identifier. While the IoT Thing name and MQTT client identifier do not need to match for the demos to run, the example policies have the Thing name and client identifier identical as per AWS IoT best practices.
It can be very helpful to also have the AWS Command Line Interface tooling installed.
You can pass the following configuration settings as command line options in order to run the mutual auth demos. Make sure to run the following command in the root directory of the C-SDK:
## optionally find your-aws-iot-endpoint from the command line
aws iot describe-endpoint --endpoint-type iot:Data-ATS
cmake -S . -Bbuild
-DAWS_IOT_ENDPOINT="<your-aws-iot-endpoint>" -DCLIENT_CERT_PATH="<your-client-certificate-path>" -DCLIENT_PRIVATE_KEY_PATH="<your-client-private-key-path>"
In order to set these configurations manually, edit demo_config.h
in demos/mqtt/mqtt_demo_mutual_auth/
and demos/http/http_demo_mutual_auth/
to #define
the following:
AWS_IOT_ENDPOINT
to your custom endpoint. This is found on the Settings page of the AWS IoT Console and has a format of ABCDEFG1234567.iot.<aws-region>.amazonaws.com
where <aws-region>
can be an AWS region like us-east-2
.aws iot describe-endpoint --endpoint-type iot:Data-ATS
.CLIENT_CERT_PATH
to the path of the client certificate downloaded when setting up the device certificate in AWS IoT Account Setup.CLIENT_PRIVATE_KEY_PATH
to the path of the private key downloaded when setting up the device certificate in AWS IoT Account Setup.It is possible to configure ROOT_CA_CERT_PATH
to any PEM-encoded Root CA Certificate. However, this is optional because CMake will download and set it to AmazonRootCA1.pem when unspecified.
To build the AWS IoT Device Defender and AWS IoT Device Shadow demos, you can pass the following configuration settings as command line options. Make sure to run the following command in the root directory of the C-SDK:
cmake -S . -Bbuild -DAWS_IOT_ENDPOINT="<your-aws-iot-endpoint>" -DROOT_CA_CERT_PATH="<your-path-to-amazon-root-ca>" -DCLIENT_CERT_PATH="<your-client-certificate-path>" -DCLIENT_PRIVATE_KEY_PATH="<your-client-private-key-path>" -DTHING_NAME="<your-registered-thing-name>"
An Amazon Root CA certificate can be downloaded from here.
In order to set these configurations manually, edit demo_config.h
in the demo folder to #define
the following:
AWS_IOT_ENDPOINT
to your custom endpoint. This is found on the Settings page of the AWS IoT Console and has a format of ABCDEFG1234567.iot.us-east-2.amazonaws.com
.ROOT_CA_CERT_PATH
to the path of the root CA certificate downloaded when setting up the device certificate in AWS IoT Account Setup.CLIENT_CERT_PATH
to the path of the client certificate downloaded when setting up the device certificate in AWS IoT Account Setup.CLIENT_PRIVATE_KEY_PATH
to the path of the private key downloaded when setting up the device certificate in AWS IoT Account Setup.THING_NAME
to the name of the Thing created in AWS IoT Account Setup.To build the AWS IoT Fleet Provisioning Demo, you can pass the following configuration settings as command line options. Make sure to run the following command in the root directory of the C-SDK:
cmake -S . -Bbuild -DAWS_IOT_ENDPOINT="<your-aws-iot-endpoint>" -DROOT_CA_CERT_PATH="<your-path-to-amazon-root-ca>" -DCLAIM_CERT_PATH="<your-claim-certificate-path>" -DCLAIM_PRIVATE_KEY_PATH="<your-claim-private-key-path>" -DPROVISIONING_TEMPLATE_NAME="<your-template-name>" -DDEVICE_SERIAL_NUMBER="<your-serial-number>"
An Amazon Root CA certificate can be downloaded from here.
To create a provisioning template and claim credentials, sign into your AWS account and visit here. Make sure to enable the "Use the AWS IoT registry to manage your device fleet" option. Once you have created the template and credentials, modify the claim certificate's policy to match the sample policy.
In order to set these configurations manually, edit demo_config.h
in the demo folder to #define
the following:
AWS_IOT_ENDPOINT
to your custom endpoint. This is found on the Settings page of the AWS IoT Console and has a format of ABCDEFG1234567.iot.us-east-2.amazonaws.com
.ROOT_CA_CERT_PATH
to the path of the root CA certificate downloaded when setting up the device certificate in AWS IoT Account Setup.CLAIM_CERT_PATH
to the path of the claim certificate downloaded when setting up the template and claim credentials.CLAIM_PRIVATE_KEY_PATH
to the path of the private key downloaded when setting up the template and claim credentials.PROVISIONING_TEMPLATE_NAME
to the name of the provisioning template created.DEVICE_SERIAL_NUMBER
to an arbitrary string representing a device identifier.You can pass the following configuration settings as command line options in order to run the S3 demos. Make sure to run the following command in the root directory of the C-SDK:
cmake -S . -Bbuild -DS3_PRESIGNED_GET_URL="s3-get-url" -DS3_PRESIGNED_PUT_URL="s3-put-url"
S3_PRESIGNED_PUT_URL
is only needed for the S3 upload demo.
In order to set these configurations manually, edit demo_config.h
in demos/http/http_demo_s3_download_multithreaded
, and demos/http/http_demo_s3_upload
to #define
the following:
S3_PRESIGNED_GET_URL
to a S3 presigned URL with GET access.S3_PRESIGNED_PUT_URL
to a S3 presigned URL with PUT access.You can generate the presigned urls using demos/http/common/src/presigned_urls_gen.py. More info can be found here.
Refer this demos/http/http_demo_s3_download/README.md to follow the steps needed to configure and run the S3 Download HTTP Demo using SigV4 Library that generates the authorization HTTP header needed to authenticate the HTTP requests send to S3.
apt install curl libmosquitto-dev
If the platform does not contain the libmosquitto
library, the demo will build the library from source.
libmosquitto
1.4.10 or any later version of the first major release is required to run this demo.
The following creates a job that specifies a Linux Kernel link for downloading.
aws iot create-job \
--job-id 'job_1' \
--targets arn:aws:iot:us-west-2:<account-id>:thing/<thing-name> \
--document '{"url":"https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.8.5.tar.xz"}'
After you build and run the initial executable you will have to create another executable and schedule an OTA update job with this image.
APP_VERSION_BUILD
in demos/ota/ota_demo_core_[mqtt/http]/demo_config.h
to a different version than what is running.build-dir-2
.mv ota_demo_core_mqtt ota_demo_core_mqtt2
build-dir-2/bin/ota_demo2
./home/ubuntu/aws-iot-device-sdk-embedded-C-staging/build-dir/bin/ota_demo_core_mqtt2
.sudo ./ota_demo_core_mqtt
or sudo ./ota_demo_core_http
.chmod 775 ota_demo_core_mqtt2
sudo ./ota_demo_core_mqtt2
Before building the demos, ensure you have installed the prerequisite software. On Ubuntu 18.04 and 20.04, gcc
, cmake
, and OpenSSL can be installed with:
sudo apt install build-essential cmake libssl-dev
cmake -S . -Bbuild && cd build
make help | grep demo
:defender_demo
http_demo_basic_tls
http_demo_mutual_auth
http_demo_plaintext
http_demo_s3_download
http_demo_s3_download_multithreaded
http_demo_s3_upload
jobs_demo_mosquitto
mqtt_demo_basic_tls
mqtt_demo_mutual_auth
mqtt_demo_plaintext
mqtt_demo_serializer
mqtt_demo_subscription_manager
ota_demo_core_http
ota_demo_core_mqtt
pkcs11_demo_management_and_rng
pkcs11_demo_mechanisms_and_digests
pkcs11_demo_objects
pkcs11_demo_sign_and_verify
shadow_demo_main
demo_name
with your desired demo then build it: make demo_name
build/bin
directory and run any demo executables from there.cmake -S . -Bbuild && cd build
make
build/bin
directory and run any demo executables from there.The corePKCS11 demos do not require any AWS IoT resources setup, and are standalone. The demos build upon each other to introduce concepts in PKCS #11 sequentially. Below is the recommended order.
pkcs11_demo_management_and_rng
pkcs11_demo_mechanisms_and_digests
pkcs11_demo_objects
pkcs11_demo_sign_and_verify
pkcs11_demo_objects
to be in the directory the demo is executed from.Install Docker:
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
Installing Mosquitto to run MQTT demos locally
The following instructions have been tested on an Ubuntu 18.04 environment with Docker and OpenSSL installed.
Download the official Docker image for Mosquitto 1.6.14. This version is deliberately chosen so that the Docker container can load certificates from the host system. Any version after 1.6.14 will drop privileges as soon as the configuration file has been read (before TLS certificates are loaded).
docker pull eclipse-mosquitto:1.6.14
If a Mosquitto broker with TLS communication needs to be run, ignore this step and proceed to the next step. A Mosquitto broker with plain text communication can be run by executing the command below.
docker run -it -p 1883:1883 --name mosquitto-plain-text eclipse-mosquitto:1.6.14
Set BROKER_ENDPOINT
defined in demos/mqtt/mqtt_demo_plaintext/demo_config.h
to localhost
.
Ignore the remaining steps unless a Mosquitto broker with TLS communication also needs to be run.
For TLS communication with Mosquitto broker, server and CA credentials need to be created. Use OpenSSL commands to generate the credentials for the Mosquitto server.
# Generate CA key and certificate. Provide the Subject field information as appropriate for CA certificate.
openssl req -x509 -nodes -sha256 -days 365 -newkey rsa:2048 -keyout ca.key -out ca.crt
# Generate server key and certificate.# Provide the Subject field information as appropriate for Server certificate. Make sure the Common Name (CN) field is different from the root CA certificate.
openssl req -nodes -sha256 -new -keyout server.key -out server.csr # Sign with the CA cert.
openssl x509 -req -sha256 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
Note: Make sure to use different Common Name (CN) detail between the CA and server certificates; otherwise, SSL handshake fails with exactly same Common Name (CN) detail in both the certificates.
port 8883
cafile /mosquitto/config/ca.crt
certfile /mosquitto/config/server.crt
keyfile /mosquitto/config/server.key
# Use this option for TLS mutual authentication (where client will provide CA signed certificate)
#require_certificate true
tls_version tlsv1.2
#use_identity_as_username true
Create a mosquitto.conf file to use port 8883 (for TLS communication) and providing path to the generated credentials.
Run the docker container from the local directory containing the generated credential and mosquitto.conf files.
docker run -it -p 8883:8883 -v $(pwd):/mosquitto/config/ --name mosquitto-basic-tls eclipse-mosquitto:1.6.14
Update demos/mqtt/mqtt_demo_basic_tls/demo_config.h
to the following:
Set BROKER_ENDPOINT
to localhost
.
Set ROOT_CA_CERT_PATH
to the absolute path of the CA certificate created in step 4. for the local Mosquitto server.
Installing httpbin to run HTTP demos locally
Run httpbin through port 80:
docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin
SERVER_HOST
defined in demos/http/http_demo_plaintext/demo_config.h
can now be set to localhost
.
To run http_demo_basic_tls
, download ngrok in order to create an HTTPS tunnel to the httpbin server currently hosted on port 80:
./ngrok http 80 # May have to use ./ngrok.exe depending on OS or filename of the executable
ngrok
will provide an https link that can be substituted in demos/http/http_demo_basic_tls/demo_config.h
and has a format of https://ABCDEFG12345.ngrok.io
.
Set SERVER_HOST
in demos/http/http_demo_basic_tls/demo_config.h
to the https link provided by ngrok, without https://
preceding it.
You must also download the Root CA certificate provided by the ngrok https link and set ROOT_CA_CERT_PATH
in demos/http/http_demo_basic_tls/demo_config.h
to the file path of the downloaded certificate.
The C-SDK libraries and platform abstractions can be installed to a file system through CMake. To do so, run the following command in the root directory of the C-SDK. Note that installation is not required to run any of the demos.
cmake -S . -Bbuild -DBUILD_DEMOS=0 -DBUILD_TESTS=0
cd build
sudo make install
Note that because make install
will automatically build the all
target, it may be useful to disable building demos and tests with -DBUILD_DEMOS=0 -DBUILD_TESTS=0
unless they have already been configured. Super-user permissions may be needed if installing to a system include or system library path.
To install only a subset of all libraries, pass -DINSTALL_LIBS
to install only the libraries you need. By default, all libraries will be installed, but you may exclude any library that you don't need from this list:
-DINSTALL_LIBS="DEFENDER;SHADOW;JOBS;OTA;OTA_HTTP;OTA_MQTT;BACKOFF_ALGORITHM;HTTP;JSON;MQTT;PKCS"
By default, the install path will be in the project
directory of the SDK. You can also set -DINSTALL_TO_SYSTEM=1
to install to the system path for headers and libraries in your OS (e.g. /usr/local/include
& /usr/local/lib
for Linux).
Upon entering make install
, the location of each library will be specified first followed by the location of all installed headers:
-- Installing: /usr/local/lib/libaws_iot_defender.so
-- Installing: /usr/local/lib/libaws_iot_shadow.so
...
-- Installing: /usr/local/include/aws/defender.h
-- Installing: /usr/local/include/aws/defender_config_defaults.h
-- Installing: /usr/local/include/aws/shadow.h
-- Installing: /usr/local/include/aws/shadow_config_defaults.h
You may also set an installation path of your choice by passing the following flags through CMake. Make sure to run the following command in the root directory of the C-SDK:
cmake -S . -Bbuild -DBUILD_DEMOS=0 -DBUILD_TESTS=0 \
-DCSDK_HEADER_INSTALL_PATH="/header/path" -DCSDK_LIB_INSTALL_PATH="/lib/path"
cd build
sudo make install
POSIX platform abstractions are used together with the C-SDK libraries in the demos. By default, these abstractions are also installed but can be excluded by passing the flag: -DINSTALL_PLATFORM_ABSTRACTIONS=0
.
Lastly, a custom config path for any specific library can also be specified through the following CMake flags, allowing libraries to be compiled with a config of your choice:
-DDEFENDER_CUSTOM_CONFIG_DIR="defender-config-directory"
-DSHADOW_CUSTOM_CONFIG_DIR="shadow-config-directory"
-DJOBS_CUSTOM_CONFIG_DIR="jobs-config-directory"
-DOTA_CUSTOM_CONFIG_DIR="ota-config-directory"
-DHTTP_CUSTOM_CONFIG_DIR="http-config-directory"
-DJSON_CUSTOM_CONFIG_DIR="json-config-directory"
-DMQTT_CUSTOM_CONFIG_DIR="mqtt-config-directory"
-DPKCS_CUSTOM_CONFIG_DIR="pkcs-config-directory"
Note that the file name of the header should not be included in the directory.
Note: For pre-generated documentation, please visit Releases and Documentation section.
The Doxygen references were created using Doxygen version 1.9.2. To generate the Doxygen pages, use the provided Python script at tools/doxygen/generate_docs.py. Please ensure that each of the library submodules under libraries/standard/
and libraries/aws/
are cloned before using this script.
cd <CSDK_ROOT>
git submodule update --init --recursive --checkout
python3 tools/doxygen/generate_docs.py
The generated documentation landing page is located at docs/doxygen/output/html/index.html
.
Author: aws
Source code: https://github.com/aws/aws-iot-device-sdk-embedded-C
License: MIT license
1597014000
Flutter Google cross-platform UI framework has released a new version 1.20 stable.
Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.
Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store. If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.
Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.
Here are the few key points of this release:
In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.
If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.
Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.
Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.
A new widget for interaction
InteractiveViewer
is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.
In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider
and RangeSlider
, DatePicker
with support for date range and time picker with the new style.
pubspec.yaml
formatOther than these widget updates there is some update within the project also like in pubspec.yaml
file format. If you are a flutter plugin publisher then your old pubspec.yaml
is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.
Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_
setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.
The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.
Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dart
method.
There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.
You can get more free Flutter tutorials you can follow these courses:
#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows
1598396940
Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking** Android and iOS** applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).
Flutter was officially released in December 2018. Since then, it has gone a much stronger flutter community.
There has been much increase in flutter developers, flutter packages, youtube tutorials, blogs, flutter examples apps, official and private events, and more. Flutter is now on top software repos based and trending on GitHub.
What is Flutter? this question comes to many new developer’s mind.
Flutter means flying wings quickly, and lightly but obviously, this doesn’t apply in our SDK.
So Flutter was one of the companies that were acquired by **Google **for around $40 million. That company was based on providing gesture detection and recognition from a standard webcam. But later when the Flutter was going to release in alpha version for developer it’s name was Sky, but since Google already owned Flutter name, so they rename it to Flutter.
Flutter is used in many startup companies nowadays, and even some MNCs are also adopting Flutter as a mobile development framework. Many top famous companies are using their apps in Flutter. Some of them here are
and many more other apps. Mobile development companies also adopted Flutter as a service for their clients. Even I was one of them who developed flutter apps as a freelancer and later as an IT company for mobile apps.
#dart #flutter #uncategorized #flutter framework #flutter jobs #flutter language #flutter meaning #flutter meaning in hindi #google flutter #how does flutter work #what is flutter
1644991598
The Ultimate Guide To Tik Tok Clone App With Firebase - Ep 2
In this video, I'm going to show you how to make a Cool Tik Tok App a new Instagram using Flutter,firebase and visual studio code.
In this tutorial, you will learn how to Upload a Profile Pic to Firestore Data Storage.
🚀 Nice, clean and modern TikTok Clone #App #UI made in #Flutter⚠️
Starter Project : https://github.com/Punithraaj/Flutter_Tik_Tok_Clone_App/tree/Episode1
► Timestamps
0:00 Intro 0:20
Upload Profile Screen
16:35 Image Picker
20:06 Image Cropper
24:25 Firestore Data Storage Configuration.
⚠️ IMPORTANT: If you want to learn, I strongly advise you to watch the video at a slow speed and try to follow the code and understand what is done, without having to copy the code, and then download it from GitHub.
► Social Media
GitHub: https://github.com/Punithraaj/Flutter_Tik_Tok_Clone_App.git
LinkedIn: https://www.linkedin.com/in/roaring-r...
Twitter: https://twitter.com/roaringraaj
Facebook: https://www.facebook.com/flutterdartacademy
► Previous Episode : https://youtu.be/QnL3fr-XpC4
► Playlist: https://youtube.com/playlist?list=PL6vcAuTKAaYe_9KQRsxTsFFSx78g1OluK
I hope you liked it, and don't forget to like,comment, subscribe, share this video with your friends, and star the repository on GitHub!
⭐️ Thanks for watching the video and for more updates don't forget to click on the notification.
⭐️Please comment your suggestion for my improvement.
⭐️Remember to like, subscribe, share this video, and star the repo on Github :)
Hope you enjoyed this video!
If you loved it, you can Buy me a coffee : https://www.buymeacoffee.com/roaringraaj
LIKE & SHARE & ACTIVATE THE BELL Thanks For Watching :-)
https://youtu.be/F_GgZVD4sDk
#flutter tutorial - tiktok clone with firebase #flutter challenge @tiktokclone #fluttertutorial firebase #flutter firebase #flutter pageview #morioh #flutter
1660665600
Criar um novo projeto Flutter é uma bênção - base de código nova, nenhum código legado (ainda), segurança nula, versões mais recentes de seus pacotes favoritos e assim por diante. Mas, ao mesmo tempo, você deve tomar decisões críticas no início do projeto que estabeleceriam as bases para o futuro, como ferramentas, pacotes, estrutura de arquivos, solução de gerenciamento de estado, plano de teste. Caso contrário, o projeto acabaria se transformando em apenas mais uma tigela de espaguete e almôndegas. Para evitar isso, preparei uma lista, na minha opinião, dos elementos mais importantes do projeto que devem ser decididos logo no início. Espero que ajude você, portanto - boa leitura!
1. Análise de código estático
Eu não vou escrever código confuso ( fonte )
O Linter é uma ferramenta de análise estática que identifica e sinaliza erros de programação, avisos, falhas de estilo em seu código para você corrigi-los. No contexto do Flutter, essa é uma das coisas mais fáceis de implementar e uma das mais úteis para manter seu código limpo.
Existem várias regras diferentes que você pode definir para o seu código seguir, mas eu recomendaria usar um dos conjuntos predefinidos que já seguem as melhores práticas baseadas no Guia de Estilo do Dart :
Qualquer que seja o pacote escolhido, você sempre pode adicionar ou remover qualquer regra de análise estática específica no arquivo analysis_options.yaml .
2. Localização (l10n)
Localização ( fonte )
O que é localização ( l10n , em suma)?
Localização é a adaptação de um produto ou serviço para atender às necessidades de uma determinada língua, cultura ou “look-and-feel” de uma população desejada. — Tech Target
É essencial construir um aplicativo que pareça natural para os usuários, por exemplo, usando as traduções corretas, formatos de data e moeda, direção do texto. Para isso, a localização é uma ferramenta fundamental a ser utilizada. Mesmo que você esteja criando um único aplicativo de região/idioma, eu ainda recomendo que você implemente a localização desde o início, separando assim seus textos do código da interface do usuário. Consequentemente, eles podem ser reutilizados e ajustados posteriormente sem afetar o código.
A documentação do Flutter explica perfeitamente o processo de internacionalização do seu aplicativo. Se a maneira padrão parecer muito complexa e/ou você precisar de algumas extensões e métodos auxiliares úteis, existem pacotes populares de terceiros, como easy_localization , que podem ajudá-lo no processo de localização.
3. Ambientes (com alguns sabores)
Ambientes de programação ( fonte )
Aposto que você já ouviu pelo menos um caso do seu ambiente (sem trocadilhos) quando alguém corrompeu dados ou excluiu toda a tabela de usuários em produção. Confie em mim - isso não é divertido. Portanto, é uma boa prática criar ambientes diferentes para o seu projeto:
Ter esses ambientes ajuda você a experimentar e verificar recursos com segurança antes que essas alterações cheguem às mãos dos usuários.
Agora, outra parte – sabores . Não, não, não estamos falando de algo doce, salgado ou azedo - esse é apenas mais um termo usado em programação para descrever diferentes variantes de compilação para seu aplicativo. Por exemplo, você deseja que o ícone e o título, o endpoint da API ou qualquer outra configuração sejam diferentes para cada ambiente específico. Para isso, você define um “sabor” diferente que é usado quando o aplicativo está sendo construído para um ambiente específico. Aqui estão alguns recursos sobre como criar sabores para o Flutter .
4. Integração Contínua e Entrega Contínua (CI/CD)
Etapas de Integração Contínua (CI) e Entrega Contínua (CD) ( fonte )
Após a introdução de diferentes ambientes, o próximo passo natural é automatizar o processo de construção, teste e liberação de seu aplicativo. CI/CD é um tópico bastante complexo por si só e eu não sou um especialista neste campo de forma alguma, portanto, eu recomendaria procurar alguns outros recursos sobre como automatizar diferentes estágios de desenvolvimento de aplicativos.
No entanto, existem muitas soluções NoOps compatíveis com o Flutter para que você possa automatizar seu processo de desenvolvimento com facilidade:
Qualquer uma dessas soluções faria o truque - basta selecionar aquela que se adapta às suas necessidades e orçamento.
5. Código de back-end
Uma vez outro meme sobre backend ( source )
Você já tem seu backend implementado em alguma linguagem de programação exótica ou talvez não tão sofisticada? Ótimo, você pode pular esta etapa, mas eu ainda recomendaria verificar algumas soluções em nuvem para referência futura.
Na versão simplificada, há duas opções para a parte de back-end do seu aplicativo:
Caso a segunda opção pareça atraente para você, existem algumas ótimas plataformas de nuvem para escolher com suporte ao Flutter:
As plataformas de nuvem fornecem autenticação, banco de dados, armazenamento, opções de API para seu aplicativo e muitos outros recursos. Qualquer uma dessas é uma ótima opção quando você só precisa validar a ideia e construir o MVP rapidamente sem gastar muito tempo na solução de back-end completa.
6. Registro, dados de falhas e análises
Ops, algo deu errado ( fonte )
O registro é subestimado – aqui, eu disse isso! Tudo está legal até que algo dê errado e você precise de informações sobre isso. Há sempre uma área cinzenta quando discutimos o que deve ser registrado e o que não deve ser registrado. Mas uma coisa é sempre clara - você deve saber quando seu aplicativo falha e o que causa o problema. Quanto mais dados você coletar sobre o incidente, mais fácil será encontrar e corrigir o problema.
Serviços como Sentry , Firebase Crashlytics , Datadog podem ajudá-lo a registrar os dados mais importantes, relatórios de falhas ou até mesmo configurar notificações quando seu aplicativo ou serviços relacionados estiverem inativos.
Outro tipo de registro é a coleta de dados do usuário para fins de análise. Quando você está construindo um produto novo, talvez único, é crucial entender as necessidades de seus usuários, seu comportamento e como eles estão usando o aplicativo. Para isso, várias ferramentas de análise podem ser integradas ao seu aplicativo Flutter, como Firebase Analytics , App Center Analytics e muito mais.
7. Marca do aplicativo
Tema do material ( fonte )
Um dos principais objetivos de qualquer aplicativo ou marca é ser reconhecível. Usar a paleta de cores, o logotipo, os ícones, os elementos de design, o conteúdo, a fonte e às vezes até o layout corretos faz com que seu produto se destaque dos demais. Isso é a marca do aplicativo , e preparar as partes fundamentais no início economizará muito tempo durante todo o projeto.
Se você já tem seu protótipo de interface do usuário ou componentes de design prontos, agora é um bom momento para transferi-los para seu aplicativo e definir temas - cores, fontes, formas, etc. Para facilitar, Mike Rydstrom criou um pacote excelente para este — flex_color_scheme .
8. Estrutura do projeto e gestão do estado
Gerenciamento de estado no Flutter ( fonte )
Sim, o polêmico. Só para deixar claro, não existe “a melhor solução de gerenciamento de estado” ou “a melhor arquitetura do aplicativo” – se alguém disser o contrário, lembre-se de que provavelmente também despeja o leite na tigela antes do cereal. E essa é a pior parte - eu não posso te ensinar a melhor maneira. Só posso fornecer várias opções ou compartilhar minhas preferências.
Várias opções de estrutura de arquivos para o próximo projeto Flutter:
Sobre a gestão estadual em Flutter — acho que estamos no ponto em que poderíamos dedicar toda a conferência a esse tópico e ainda não ter uma resposta final depois. Apenas para adicionar meus dois centavos, escolha aquele com o qual você se sente mais confortável. Você pode encontrar uma lista abrangente de opções aqui .
9. Geração de código
Geração de código ( fonte )
Se você quiser cortar alguns cantos e economizar algum tempo de desenvolvimento, você pode usar a geração de código em seu projeto. Codifique menos, entregue mais !
Há uma variedade de ferramentas diferentes para usar, seja trabalhando com localizações, ativos, analisando JSON, gerando classes de modelo, implementando localizador de serviços, roteamento ou trabalhando com estados imutáveis. A única coisa a fazer é investigar as ferramentas e pacotes disponíveis e escolher os melhores para cobrir as necessidades do seu projeto.
Para um início rápido do projeto Flutter, eu recomendaria verificar o Very Good CLI . Isso economizaria várias horas de configuração (infelizmente, aprendi da maneira mais difícil).
Além disso, no mês passado eu dei uma palestra sobre geração de código — pode ser um ponto de partida para sua jornada de geração de código Flutter, então confira!
10. Estratégia de teste
Teste de aplicativos ( fonte )
É bom ou ruim cobrir 100% do seu código com testes? Claro, é incrível, mas a que custo? Pensando dessa forma, você pode cair no poço condenado onde você gasta mais tempo escrevendo testes do que desenvolvendo recursos. Para evitar isso, você precisa de uma estratégia de teste.
Não me entenda mal — cobrir seu código com testes é ótimo e quanto mais lugares obscuros do seu código forem cobertos, mais seguro você se sentirá ao implementar novos recursos. Apenas, na minha opinião, você deve encontrar o equilíbrio onde os testes ainda trazem mais valor em comparação com o tempo gasto em escrevê-los. Por exemplo, esta é a minha estratégia de teste:
Honestamente, ainda estou procurando essa média de ouro nos testes, mas você fica melhor nisso projeto após projeto, confie em mim.
11. Arquivo LEIA-ME
Faça um README ( fonte )
Você me ouviu direito - documentação. O arquivo README é o documento mais importante do projeto, principalmente quando se trabalha em equipe.
Você acabou de introduzir uma nova solução que requer geração de código? Você acabou de adicionar um novo script bash útil para automatizar o processo? Você implementou um registrador global que DEVE ser usado em todos os lugares do projeto? Não podemos ler sua mente - mencione isso no arquivo README!
Não existe muita documentação (pelo menos eu não estive em tal situação), apenas a falta de informações sobre o projeto e o código. Todos os comandos para gerar, testar e executar o código, várias decisões de estrutura de arquivos, diagramas, ferramentas e serviços externos, informações sobre diferentes ambientes (SEM CHAVES SECRETAS) devem ser colocados aqui e mantidos em um único local. Este é um trabalho chato, mas muito gratificante!
Ufa, que passeio… ( fonte )
É isso! Obrigado pelo seu tempo lendo este artigo.
Perdi alguma coisa? Mencione isso nos comentários! Qual é a sua lista de verificação ao criar um novo aplicativo Flutter?