No-code App Development Using FlutterFlow
Are you looking to revolutionize your app development workflow?
Look no further than FlutterFlow – an innovative visual development platform that’s taking app development to the next level with its intuitive Drag & Drop functionality. In this blog post, we’ll dive into what FlutterFlow is, its key features, and how you can use it to rapidly bring your app ideas to life.
What is FlutterFlow?
At its core, FlutterFlow is a powerful visual development platform designed to simplify and accelerate the process of building mobile and web applications. It’s built on top of Google’s Flutter framework, which is renowned for its ability to create high-quality, natively compiled applications for mobile, web, and desktop from a single codebase.
FlutterFlow takes the power of Flutter and adds an intuitive drag-and-drop interface, making it accessible to developers of all skill levels. Whether you’re a seasoned developer or just starting out, you can leverage FlutterFlow to design, develop, and deploy apps without the need for extensive coding knowledge.
Key Features of FlutterFlow
1. Visual Interface: FlutterFlow offers a visual interface that lets you design your app’s user interface by simply dragging and dropping elements onto the canvas. This speeds up the design process and ensures a pixel-perfect result.
2. Widgets Gallery: The platform provides a wide range of pre-built widgets that you can customize to match your app’s design. From buttons and text fields to complex interactive components, FlutterFlow has you covered.
3. Responsive Design: Building apps that look great on various devices is essential. FlutterFlow enables you to create responsive layouts that adapt seamlessly to different screen sizes and orientations.
4. Data Binding: Connect your app’s UI to data sources easily. FlutterFlow allows you to bind data from APIs or databases to your UI components, keeping your app’s content up-to-date.
5. Collaboration: Collaborate with team members in real-time. Whether you’re a solo developer or part of a team, FlutterFlow supports seamless collaboration, enhancing productivity.
Getting Started with FlutterFlow
1. Sign Up: To get started, sign up for a FlutterFlow account. You can choose from different pricing plans based on your needs.
2. Create a New Project: Once you’re in, create a new project and choose whether you’re building a mobile or web app.
3. Design Your App: Use the visual editor to design your app’s UI. Drag and drop widgets onto the canvas, arrange them, and customize their properties.
4. Add Functionality: Use the built-in logic builder to add functionality to your app. Define interactions, create conditional statements, and more – all without writing extensive code.
5. Preview and Test: Before deploying your app, use the preview feature to test how it looks and functions. Make adjustments as needed to ensure a seamless user experience.
6. Deploy Your App: Once you’re satisfied with your app, deploy it with just a few clicks. FlutterFlow takes care of the technical details, allowing you to focus on delivering an exceptional app.
Conclusion
In the fast-paced world of app development, tools like FlutterFlow are a game-changer. They empower developers to create robust and visually stunning applications without the worry of traditional coding methods. By harnessing the power of Google’s Flutter framework and adding a user-friendly visual interface, FlutterFlow is designed to redefine how we approach app development.
So whether you’re a startup founder looking to build a prototype, a developer aiming to speed up your workflow, or someone passionate about turning your app ideas into reality, FlutterFlow has everything you need to succeed.
For more information, please head over to our Hire Flutter Developer page and to develop a custom mobile application using Flutter, Hire Flutter Developer at HK Infosoft – we are destined to provide you with an innovative solution using the latest technology stacks. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
Content Source:
- flutterflow.io
What is Pair Programming?
Two Minds, One Goal: The Power of Pair Programming
Pair programming is an agile software development technique in which two developers work together on the same computer to write code. One developer, called the driver, is responsible for typing the code while the other, called the observer, review the code and makes suggestions. The two developers then switch roles, with the observer becoming the driver and the driver becoming the observer.
The story of pair programming originates from a software development company called Chrysler. In the late 1990s, Chrysler was tasked with developing a new software system for its payroll operations. The project was behind schedule and the team was struggling to make progress. In desperation, the lead programmer, Xitij Kothi, suggested an unconventional solution: pair programming. He proposed that two programmers work together on each task, with one writing code while the other reviews and offers suggestions.
The strategy worked. The project was completed on time and the quality of the software was far superior to what had been expected. Since then, pair programming has become a widely accepted practice in software development.
Pair programming can reduce the time it takes to complete a task by allowing two developers to work together more effectively. By having two developers work side-by-side, they can quickly identify and resolve problems as they occur. The navigator can also provide insights into potential issues before they become problems, helping to reduce the amount of debugging and testing that needs to be done. Additionally, pair programming enables developers to learn from each other, which can help reduce the amount of time it takes to complete a task.
Pair programming also helps to spread knowledge and skills among the team members, as each programmer learns from the other. This can be especially useful in distributed software projects, where team members may be geographically dispersed.
Story Time
John and Jane had been classmates for the past couple of months, but never really got to know each other very well. They had been assigned a project in their programming class and had decided to work together.
John was very knowledgeable in the subject and had a good understanding of what was expected. Jane, on the other hand, had little to no experience with programming but was eager to learn. Together, they decided to use the pair programming technique.
John and Jane sat down together and discussed their project. John explained the concept of pair programming, how it works, and what their roles would be. Jane was very willing to learn and was excited to get started.
John and Jane began writing the code for their project. John took the lead and wrote most of the code while Jane watched and asked questions. Whenever Jane found a mistake or had an idea, she would suggest it to John, who would then incorporate it into the code.
In this way, John and Jane worked together to complete their project. By the end of it, both of them had gained a better understanding of programming and had come to know each other better.
“Pair programming had become a regular part of John and Jane’s programming class ever since.”
Issues we can face during Pair Programming and its Solutions
One type of problem that programmers can face during pair programming is communication breakdown. This is when two programmers are unable to effectively communicate with each other due to a lack of understanding or different working styles. To overcome this issue, it is important to ensure that both programmers are on the same page before starting to program. This can be done by discussing the problem, breaking it down into small manageable parts, and discussing how to approach it. It is also important to ensure that there is an equal amount of speaking and listening between the two programmers. It is also important to be aware of any language or cultural differences that may be present and to adjust your communication accordingly.
Different abilities can be a problem during pair programming because one programmer may be more knowledgeable or experienced in a certain area than the other. This can lead to the more experienced programmer taking on a larger share of the work, leaving the less experienced programmer feeling frustrated or left out.
To overcome this, the two partners should agree on a division of tasks based on their respective strengths. For example, if one partner is more experienced with databases, they can take the lead on designing and setting up the database structure, while the other partner focuses on developing the business logic. Both partners should aim to challenge each other and provide feedback and support to ensure that the project is completed to the highest standard. Additionally, the partners should regularly rotate tasks so that both have the opportunity to learn from each other and gain a more comprehensive understanding of the project.
Task division can be a problem during pair programming if one person takes on more responsibility than the other, leaving the other feeling like they’re not contributing as much to the project. This can lead to frustration and resentment, and can ultimately undermine the collaborative nature of pair programming. To overcome this, the two people should agree on how they will divide the tasks before they begin.
For example, they can decide that one person will take the lead on the coding while the other focuses on debugging and testing, or that each person will take turns writing sections of code. They should also make sure to have regular check-ins to discuss progress, address any issues, and ensure that both parties are on the same page. This will help ensure that both parties feel like they’re contributing equally to the project.
Distractions can be a major problem during pair programming, as they can prevent the pair from focusing on their task and completing it in a timely manner. Distractions could include anything from phones, emails, instant messages, or conversations with other people in the same room. To overcome distractions during pair programming, both partners should agree to have their phones on silent and out of sight. If possible, they should also try to find a quiet space where they can work without interruption. Additionally, they should set aside specific times to check emails and other messages and then get back to their task. They should also set specific goals and deadlines for the task ahead of time to help keep them on track.
one person may be more accustomed to writing code with fewer lines and using terse abbreviations, while the other person may prefer longer and more descriptive lines of code. This can lead to a lot of back and forth, which can slow down the programming process. To overcome this problem, it is important to have open communication and be respectful of each other’s coding styles. The pair should discuss their preferences and try to come to an agreement on which style they should use. They should also discuss the types of coding conventions they want to follow and agree on a coding style guide. Additionally, they should take time to explain their code to each other, as this can help them better understand each other’s coding styles. Finally, they should be open to feedback and criticism and be willing to compromise.
Conclusion
The importance of pair programming lies in its ability to improve the quality of code while also reducing the time it takes to develop software.
What’s new in Flutter 3.3
Only three months ago Google announced Flutter 3, a massive milestone that included stable support for all platforms! The good news is that the momentum since this major release has not slowed down. Since the release of Flutter 3, Flutter has merged 5,687 pull requests.
This release brings updates to Flutter web, desktop, text handling improvements in performance — and much more!
Framework
Global Selection
Until now, Flutter web apps didn’t match the expected behavior when attempting to select text. Like Flutter apps, native web applications are composed of a tree of elements. In a traditional web app, you can select multiple web elements with a single sweeping gesture, something that couldn’t be easily done on a Flutter web app.
Today that all changes! With the introduction of the SelectableArea widget, any child of the SelectableArea widget has selection enabled for free!

Pic courtesy: medium.com
To take advantage of this powerful new feature, simply wrap your route body (such as the Scaffold) with the SelectionArea widget and let Flutter do the rest.
Trackpad input
Flutter 3.3 provides improved support for trackpad input. This not only provides richer and smoother control but also reduces misinterpretation in certain cases. For an example of this misinterpretation, check out the Drag a UI element page in the Flutter cookbook. Scroll to the bottom of the page to get to the DartPad instance, and perform the following steps:
- Size the window smaller so that the upper part presents a scrollbar
- Hover over the upper part
- Use a trackpad to scroll
- Prior to installing Flutter 3.3, scrolling on a trackpad drags the item because Flutter was dispatching emulated general events
- After installing Flutter 3.3, scrolling on a trackpad correctly scrolls the list because Flutter is delivering the “scrolling” gesture, which isn’t recognized by the cards, but is recognized by the scroll view
Scribble
Flutter now supports Scribble handwriting input using the Apple Pencil on iPadOS. This feature is enabled by default on CupertinoTextField, TextField, and EditableText. To enable this feature for your end users, simply upgrade to Flutter 3.3.

Pic courtesy: medium.com
Text input
To improve support for rich text editing, this release introduces the ability to receive granular text updates from the platform’s TextInputPlugin. Previously, the TextInputClient only delivered the new editing state with no delta between the old and new, TextEditingDeltas and the DeltaTextInputClient fill this information gap. Having access to these deltas allows you to build an input field with styled ranges that expand and contract as you type.
Material Design 3
The Flutter team continues to migrate more Material Design 3 components to Flutter. This release includes updates to IconButton, Chips, and large and medium variants for AppBar.
IconButton

Pic courtesy: medium.com
Chip

Pic courtesy: medium.com
Medium and large AppBar

Pic courtesy: medium.com
Desktop
Windows
Previously, the Windows desktop application’s version was set by a file specific to the Windows application. This behavior was inconsistent with the way other platforms set their versions.
Windows desktop application versions can now be set from your projects pubspec.yaml file and build arguments. This makes it easier to enable auto updates for your end customers to get the latest and greatest when an application update is pushed.
Packages
go_router
When designing apps with complex navigation needs, things can get pretty hard to wrap your head around. To extend Flutter’s native navigation API, the team has published a new version of the go_router package, making it simpler to design routing logic that works across mobile, desktop, and the web.
The go router package, maintained by the Flutter team, simplifies routing by providing a declarative, url-based API, making it easier to navigate and handle deep-links. The latest version (4.3) enables apps to redirect using asynchronous code, and includes other breaking changes described in the migration guide.
VS Code extension enhancements
The Visual Studio Code extension for Flutter has several updates including improvements for adding dependencies. You can now add multiple, comma-separated dependencies in one step using Dart: Add Dependency.

Pic courtesy: medium.com
Performance
Raster cache improvements
This release increases the performance of loading images from assets by eliminating copies and reducing Dart garbage collection (GC) pressure. Previously, when loading asset images, the ImageProvider API required the compressed data to be copied multiple times. First, it was copied into the native heap when opening the asset and exposing it to Dart as a typed data array. Then, it was copied a second time when that typed data array was copied to the internal storage of a ui.ImmutableBuffer.
With the addition of ui.ImmutableBuffer.fromAsset, compressed image bytes can be loaded directly into the structure used for decoding. This approach requires changes to the byte loading pipeline of ImageProviders. This process is also faster because it bypasses some additional scheduling overhead required bythe previous method channel-based loader. In particular, image loading time improved by nearly 2x in our microbenchmarks.

Pic courtesy: medium.com
Stability
iOS pointer compression disabled
In the 2.10 stable release, they enabled Dart’s pointer compression optimization on iOS.Dart’s pointer compression works by reserving a large virtual memory region for Dart’s heap. Since the total virtual memory allocation allowed on iOS is less than on other platforms, this large reservation reduces the amount of memory available for use by other components that reserve their own memory, for example, Flutter plugins.
While disabling pointer compression increases the memory consumed by Dart objects, it also increases the memory available for non-Dart parts of a Flutter application, which is more desirable overall.
Apple provides an entitlement that can increase the maximum allowed virtual memory allocation for an application, however this entitlement is only supported on newer iOS versions, and wouldn’t work on devices running versions of iOS that Flutter still supports. When we are able to use this entitlement everywhere, we intend to revisit this optimization.
For more information and to develop mobile apps using Flutter, Hire Flutter Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop Mobile Apps using Flutter, please visit our technology page.
Content Source:
- medium.com
What’s new in Flutter 3
The recent release of Flutter v3.0 is now stable for macOS and Linux, in addition to Windows!
There are several exciting things coming as part of this release, including the update on Flutter’s support for macOS and Linux, significant performance improvements, mobile and web updates — and much more!
Ready for production on all desktop platforms
Linux and macOS have reached stable and include the following features:
Cascading menus and support for the macOS system menu bar
You can now create platform-rendered menu bars on macOS using the PlatformMenuBar widget, which supports the insertion of platform-only menus, and control over what appears in the macOS application menus.
Full support for international text input on all desktop platforms
International text input, including for languages that make use of text input method editors (IMEs) such as Chinese, Japanese, and Korean is fully-supported on all three desktop platforms, including third-party input methods such as Sogou and Google Japanese Input.
Accessibility on all desktop platforms
Flutter for Windows, macOS, and Linux supports accessibility services such as screen-readers, accessible navigation, and inverted colors.
Universal binaries by default on macOS
As of Flutter 3, Flutter macOS desktop apps are built as universal binaries, with native support for both existing Intel-based Macs and Apple’s latest Apple Silicon devices.
Deprecating Windows 7/8 for development
With this release, it has raised the recommended Windows version for development to Windows 10. While there isn’t any blocking development on older versions (Windows 7, Windows 8, Windows 8.1), these versions are no longer supported by Microsoft and there is limited testing on these releases.
Mobile updates
Updates to mobile platforms include the following:
Foldable phone support
The Flutter 3 release supports foldable mobile devices. In a collaboration spearheaded by Microsoft, new features and widgets allow you to create dynamic and delightful experiences on foldable devices.
As part of this work, MediaQuery now contains a list of DisplayFeatures, describing the bounds and states of device elements like hinges, folds, and cutouts. Additionally, the DisplayFeatureSubScreen widget now positions its child widget without overlapping the bounds of DisplayFeatures, and has already been integrated with the framework’s default dialogs and pop-ups, making Flutter aware and responsive to these elements out of the box.

Pic courtesy: medium.com
iOS variable refresh rate support
Flutter now supports variable refresh rate on iOS devices with ProMotion displays, including iPhone 13 Pro and iPad Pro. On these devices, Flutter apps can render at refresh rates reaching 120 hz, which were previously limited to 60 hz. This results in a smoother experience during fast animations such as scrolling. See flutter.dev/go/variable-refresh-rate for more details.
Gradle version update
If you create a new project with the Flutter tool, you might notice that the generated files now use the latest versions of the Gradle and Android Gradle plugins. For existing projects, you need to manually bump the versions to 7.4 for Gradle, and 7.1.2 for the Android Gradle plugin.
Web updates
Updates for web apps include the following:
Image decoding
Flutter web now automatically detects and uses the ImageDecoder API in browsers that support it. As of today, most Chromium-based browsers (Chrome, Edge, Opera, Samsung Browser, and more) have added this API.
The new API decodes images asynchronously off the main thread using the browser’s built-in image codecs. This speeds up image decoding by 2x, and it never blocks the main thread, removing all jank that was previously caused by images.
Web app lifecycles
The new lifecycle API for Flutter web apps gives you the flexibility to control the bootstrap process of your Flutter app from the hosting HTML page, and helps Lighthouse analyze the performance of your app. This applies to many use-cases, including the following frequently requested scenarios:
A splash screen.
A loading indicator.
A plain HTML interactive landing page displayed before the Flutter app.
Tooling updates
Updates to Flutter and Dart tooling include:
Updated lint package
Version 2.0 of the lint packages have been released:
Flutter: https://pub.dev/packages/flutter_lints/versions/2.0.0
Dart: https://pub.dev/packages/lints/versions/2.0.0
Apps generated in Flutter 3 with flutter create automatically enable the v2.0 sets of lints. Existing apps, packages, and plugins are encouraged to migrate to v2.0 to follow the latest and greatest best practices in the Flutter world, by running flutter pub upgrade –major-versions flutter_lints.
Most of the newly added lint warnings in v2 come with automated fixes. So, after upgrading to the latest package version in your app’s pubspec.yaml file, you can run dart fix —-apply over your code base to fix most lint warnings automatically (some warnings still require some manual work). Apps, packages, or plugins that aren’t using package:flutter_lints yet can migrate by following the migration guide.
Performance improvements
Thanks to open source contributor knopp, partial repaint has been enabled on Android devices that support it. In our local testing this change cut average, 90th percentile, and 99th percentile frame rasterization times on the backdrop_filter_perf benchmark on a Pixel 4 XL device by 5x. Partial repaint when there is a single rectangular dirty region is now enabled on both iOS and newer Android devices.
It has further improved the performance of opacity animations in simple cases. In particular, when an Opacity widget contains only a single rendering primitive, the saveLayer method that is usually invoked by Opacity is omitted. In a benchmark constructed to measure the benefits of this optimization, rasterization time for this case improved by an order of magnitude.
More exciting updates
Other updates to the Flutter ecosystem include the following:
Material 3
Flutter 3 supports Material Design 3, the next generation of Material Design. Flutter 3 provides opt-in support for Material 3; this includes Material You features like dynamic color, an updated color system and typography, updates to many components, and new visual effects introduced in Android 12 like a new touch ripple design and a stretch overscroll effect. Try the Material 3 features in the new Take your Flutter app from Boring to Beautiful codelab.
For more information and to develop mobile apps using Flutter, Hire Flutter Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop Mobile Apps using Flutter, please visit our technology page.
Content Source:
- medium.com
What’s new in Flutter 2.10
We can’t believe it’s time again for a Flutter 2.10 stable release!
There are several exciting things to announce as part of this release, including a big update on Flutter’s support for Windows, several significant performance improvements, new support for icons and colors in the framework, and some tooling improvements. In addition, we’ve got some updates on the removal of the dev channel, reduction in support for older versions of iOS, and a short list of breaking changes. Let’s get to it!
Ready for production apps on Windows
First and foremost, the Flutter 2.10 release brings with it the stable release of Windows support. You no longer need to flip a flag to get the functionality that produces Windows apps on the stable channel of Flutter — now it’s available by default!
Of course, we did a lot more than just flip a flag. This release includes extensive improvements for text handling, keyboard handling, and keyboard shortcuts, as well as new integrations directly into Windows, with support for command-line arguments, globalized text entry, and accessibility.
For much more on the Windows stable launch, see the Announcing Flutter for Windows blog post, which describes the architecture of Flutter on Windows that allows for deep integration and gives you a sense of just how many Flutter packages and plugins already support Windows. You can also see some examples of what our tooling and app partners are doing with Flutter on Windows!
Performance improvements
This release of Flutter includes initial support for dirty region management provided by Flutter community member knopp. He’s enabled partial repaints for a single dirty region on iOS/Metal. This change reduced 90th and 99th percentile rasterization times on a few benchmarks by an order of magnitude, and reduced GPU utilization on these benchmarks from more than 90% to less than 10%.

Pic courtesy: medium.com
We expect to bring the benefits of partial repaints to other platforms in future releases.
In the Flutter 2.8 release, we landed our own internal picture recording format. Now in Flutter 2.10, we’ve started building optimizations with it. As an example, one common case of opacity layers is now implemented much more efficiently. Even in the worst case, frame raster times in our benchmarks fell to under a third of their previous value.

Pic courtesy: medium.com
We expect this optimization to expand to cover more cases as we continue developing the picture recording format.
In profile and release modes, Dart code is compiled ahead of time to native machine code. The key to the efficiency and small size of this code is a whole program type flow analysis that unlocks many compiler optimizations and aggressive tree-shaking. However, as the type flow analysis must cover the whole program, it can be somewhat expensive. This release includes a faster implementation of type flow analysis. Overall build time for the Flutter app in our benchmarks fell by ~10%.

Pic courtesy: medium.com
As always, performance enhancements, reduced memory usage, and reduced latency are a priority for the Flutter team. Look forward to further improvements in future releases.
iOS updates
In addition to performance improvements, we’ve also added some platform-specific features and enhancements. One new enhancement is smoother keyboard animations in iOS from luckysmg, which is provided automatically to your app without you having to do a thing.

Pic courtesy: medium.com
We’ve also improved the stability of the camera plugin for iOS by fixing a few edge case crashes.
Finally, 64-bit iOS architectures get a new feature to reduce memory usage: compressed pointers.
A 64-bit architecture represents pointers as a 8-byte data structure. When you have a lot of objects, the space taken up by the pointers themselves adds to the overall memory usage of your app, especially if you have larger, more complicated apps that have more GC churn. However, your iOS app is very unlikely to have enough objects to require a significant portion of even the 32-bit address space (2 billion objects), let alone the enormity of the 64-bit address space (9 million billion objects).
Compressed pointers were provided in Dart 2.15 and in this release of Flutter, we use them to reduce the memory usage for 64-bit iOS apps. You can check out the Dart 2.15 blog post for details.
And while you’re reading Dart blog posts, don’t forget to check out the Dart 2.16 announcement for updates on supporting Flutter for Windows with package platform tagging and a new search experience on pub.dev.
Android updates
This release contains a number of improvements for Android as well. By default, when you create a new app, Flutter defaults to support the latest version of Android, version 12 (API level 31). Also, in this release, we’ve enabled multidex support automatically. If your app supports Android SDK versions below 21, and it exceeds the 64K method limit, simply pass the –multidex flag to flutter build appbundle or flutter build apk and your app will support multidex.
And last but not least, we listened to your feedback that Gradle error messages can be intimidating. For this reason, the Flutter tool now suggests resolution steps to common issues. For example, if you add a plugin to your app that requires you to increase the minimum supported Android SDK version, you now see a “Flutter Fix” suggestion in the logs.

Pic courtesy: medium.com
We continue to add more suggestions to common error messages, and would love to get your feedback on other error messages where this treatment would be useful.
Web updates
This release contains some improvements on the web as well. For example, in previous releases, when scrolling to the edge of a multiline TextField on the web, it wouldn’t scroll properly. This release introduces edge scrolling for text selection: when the selection moves outside of the text field, the field scrolls to view the scroll extent. This new behavior is available for both web and desktop apps.

Pic courtesy: medium.com
In addition, this release of Flutter includes another notable improvement in the web. We’re always looking to reduce the overhead of our mapping of Flutter to the web. In previous versions, every time we wanted to bring a native HTML widget into your Flutter app, we needed an overlay as part of our platform view support for the web. Each one of these overlays enables custom painting but represents a certain amount of overhead. If you have a large number of native HTML widgets in your app, such as links, that adds up to a lot of overhead. With this release, we’ve created a new “non-painting platform view” for the web that essentially removes that overhead. And we’ve taken advantage of this optimization in the Link widget, which means if you have many links in your Flutter web app, they no longer represent any significant overhead at all. We’ll be applying this optimization to other widgets over time.
For more information and to develop mobile apps using Flutter, Hire Flutter Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop Mobile Apps using Flutter, please visit our technology page.
Content Source:
- medium.com
What’s new in Flutter 2.8
Flutter aims to change how apps are built. It unites mobile, web, desktop, and embedded development into a single toolkit: letting developers focus first on what they want to build, rather than which platforms they want to target; offering a high-performance, high-productivity framework that shortens the inner loop for developers; and enabling one codebase to target multiple platforms and form factors.
New features and improvements: faster and more productive
One of the major areas of focus for this release is mobile performance. Ideally great performance would come for free, but in practice any complex app needs optimization to make sure it uses the underlying hardware and libraries well. That includes startup performance, which can be constrained by network bandwidth or other initialization costs; memory usage, particularly on memory-constrained devices; and graphics rendering. We’ve been using some of our experiences with large Google apps like Google Pay to invest both in making Flutter itself more performant, and in giving you better tooling to guide profiling and optimization of your own app. Your apps should start faster and use less memory just by upgrading to Flutter 2.8.
The latest update makes it easier than ever to connect apps to back-end services, such as Firebase and Google Cloud. It adds production-quality support for Google Ads and major upgrades to the camera and embedded web plugins. The release also includes Dart 2.15, which adds major improvements to concurrency, new language features like constructor tearoffs and enhanced enumerations, and optimizations that deliver a 10% reduction in memory utilization.

With the new developer productivity enhancements to Flutter, an app can support sign-in to multiple authentication services with just a single drop-in widget.
Pic courtesy: medium.com
Another big theme of investment in this release that you’ll see us carry forward into future releases is further improving developer productivity. With features like stateful hot reload, we’ve always focused on creating a tight inner loop for developers. We’re now starting to explore some higher-level abstractions that make it easier for developers to get running faster. For example, in this release we’re adding a sign-in widget that uses Firebase to handle authentication. With this widget, you don’t have to worry about all the edge cases of sign-in, such as two-factor authentication or reset password user flows, nor about the complexities of supporting Google, Apple, Twitter, or Facebook as an auth provider. Features like this, building on the core foundations of Flutter, have the potential to transform how developers build apps, combining the development speed of low-code solutions with the flexibility and power of a full UI framework.
Both Flutter 2.8 and Dart 2.15 are available now, and should be an easy upgrade for existing apps running the previous version. For greater detail, we have a technical blog post covering the enhancements in each of Dart and Flutter.
Casual game development with Flame
For most developers, Flutter is an app framework. But there’s also a growing ecosystem around casual game development, taking advantage of the hardware-accelerated graphics support provided by Flutter.
Today, we are thrilled to celebrate the 1.0 release of Flame, a modular 2D game engine built on top of Flutter. Flame provides what you need to build games quickly: as well as a game loop, it also includes core primitives such as a component system, animated sprites and images, collision detection, a world camera, an effects system, and gesture and input support.
Flame is modular and can also be extended with packages that offer integrations to other libraries, for instance Rive (for animations), audioplayers (for music and sound effects), Forge2D (a Box2D-style physics engine), Tiled (tile maps editor), Fire Atlas (a sprite sheet and animation editor). Together, Flame and the broader ecosystem offer a strong set of services for a casual or 2D game developer.

Tomb Toad, Gravity Runner and Bonfire: three examples of games built with Flame.
Pic courtesy: medium.com
Flame is created by Blue Fire, a group of contributors focusing on creating open source packages and plugins for Flutter and Dart. We’re delighted to partner with them and encourage you to check out Flame if you’re interested in game development.
Flutter’s continued momentum
We’re amazed to see how fast Flutter continues to grow, with a flourishing ecosystem of apps and tools that build on top of the core framework. At this year’s Google I/O event, we noted that there were already over 200,000 apps built with Flutter in the Play Store. In just over six months since that event, the number of Flutter apps has nearly doubled, with more than 375,000 Flutter apps now in the Play Store.

Flutter supports Android, iOS, iPadOS, web, Windows, macOS and Linux: so you don’t have to rewrite your app just to target a different device or form factor.
Pic courtesy: medium.com
Flutter isn’t just used on Android, of course. According to independent mobile analyst firm AppAnnie, apps using Flutter on iOS include top brands and apps including BMW, eBay, WeChat, SHEIN, Philips Hue, Norton, trip.com and Greggs. On the web, Flutter is finding a home for app experiences, benefitting design tools like FlutterFlow and Rive. On desktop, the Ubuntu engineering team continues to build a variety of new experiences with Flutter, including a new installer and firmware updater. Even games like PUBG are finding that Flutter is a great fit for UI screens.
Ecosystems take a long time to build, but Flutter is now the most popular multi-platform toolkit, as measured independently by Statista, JetBrains, SlashData, and Stack Overflow. We don’t take that for granted, but the growth of Flutter’s popularity leads to an ever broader ecosystem of packages and tools that support it.
For more information and to develop mobile apps using Flutter, Hire Flutter Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop Mobile Apps using Flutter, please visit our technology page.
Content Source:
- medium.com
Announcing XD to Flutter v2.0!
Flutter is Google’s open-source UI toolkit for building beautiful apps for mobile, desktop, web, and embedded devices from a single codebase. Over the last couple of years, it has become the leading choice for developers who want to build apps for multiple platforms; but designers need a visual tool for prototyping and creating Flutter UI, rather than handcrafting Dart source code. Enter XD to Flutter!
It’s been almost a year since the first preview release of the plugin, and we’ve continued to refine and improve it with a handful of minor updates, a major v1.0 launch last summer, and now a v2.0 release to match with the launch of Flutter 2!
Wait, what is XD to Flutter?
The name probably gives it away, but the XD to Flutter plugin is a powerful, easy-to-use tool to export your stunning Adobe XD designs into clean, functional code for Flutter. You can copy code for specific visual elements from your design, export reusable widgets, or even entire views.
That means that, with the XD to Flutter plugin, you can get your designs running on virtually any device with the click of a button. It’s not going to code your whole app for you, but it’ll give you a head start.
XD to Flutter is built by gskinner in partnership with Adobe, and is published as a plugin for Adobe XD itself, so you can use it with any existing Adobe XD design you’re building.
Awesome! So what’s new?
The initial release of XD to Flutter had great support for outputting all the different visual elements in a design — vector graphics, images, rich text, background blurs, blend modes, shadows, and similar — but the result could be static and inflexible.
While it was handy for grabbing an icon or text style, we wanted it to do more! XD empowers designers to create dynamic UIs, with tools like responsive layout, scrollable areas, stacks, and grids; we want the plugin to support every one of those capabilities, and with v2.0 we’ve made a lot of progress.
Responsive Resize
XD to Flutter supports the responsive layout features of XD, which lets you “pin” elements within their enclosing parent and precisely control how they resize.

Responsive design in Adobe XD
Pic courtesy: medium.com

Responsive resize in Flutter
Pic courtesy: medium.com
This is achieved in Flutter by using a custom Pinned layout widget in the open-source adobe_xd package that developers can leverage directly in their projects.

Pinned widget code example
Pic courtesy: medium.com
Stacks & Scroll Groups
“Stacks” and Scroll Groups provide new ways to lay out content on-screen dynamically in Adobe XD. Stacks in XD let you arrange a bunch of different elements in a horizontal or vertical list, with varying spacing between them; they are more similar to a Flex widget in Flutter than their namesake Stack widget.
Scroll Groups predictably let you define an area to scroll a larger group of content vertically or horizontally, right inside your design.
XD to Flutter v2.0 supports both of these features, converting them into common Flutter widgets (Column, Row, and SingleChildScrollView). You can even put a stack into a scroll group to easily create a scrolling list of items.

Stacks & Scroll Groups in XD (left) and Flutter (right)
Pic courtesy: medium.com
Padding & Background Elements
Another new feature is background elements, which let you designate a visual element as the background for a group. This can be paired with padding to space the background’s edges from the content.
The Flutter export uses a Stack widget to layer the background element behind the content, which is placed into a Padding widget.

Padding & Background in XD (left) and Flutter (right)
Pic courtesy: medium.com
Flutter 2 & null safety
The layout features described above enable much more responsive UI, complimenting Flutter 2’s increased support for form factors like desktop and web.
Flutter 2 also introduces sound null safety — a language feature that helps developers catch nullability issues before they cause problems in apps. XD to Flutter v2.0 includes a new setting to “Export Null Safe Code”, ensuring that the generated code is future-ready.

“Export Null Safe Code” setting and output
Pic courtesy: medium.com
Sounds great! How do we get started?
Whether you’re using it to copy the code for a tricky gradient, or to export fully responsive, parameterized, interactive widgets, it’s simple to join the thousands of creative professionals that are already using the XD to Flutter plugin.
You can install it by selecting “Browse Plugins…” from Adobe XD’s “Plugin” menu and searching for “Flutter” (strangely, searching for “XD to Flutter” doesn’t work),

Pic courtesy: medium.com
Once you have it installed, open the XD to Flutter panel from the plugins panel, and tap the “Need help?” link to check out the plugin documentation.
Flutter 2 is an exciting step forward for the framework, with a focus on building beautiful apps that run virtually anywhere. At gskinner, we’re thrilled to be working with Adobe and Google to ensure that XD to Flutter continues to make the process of faithfully translating a delightful design to a working product even easier.
Stay tuned for more exciting updates to the plugin soon!
For more information and to develop mobile apps using Flutter, Hire Flutter Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop Mobile Apps using Flutter, please visit our technology page.
Content Source:
- medium.com
What’s new in Flutter 2
Web
As of today, Flutter’s web support has transitioned from beta to the stable channel. With this initial stable release, Flutter pushes reusability of code to another level with the support of the web platform. So now when you create a Flutter app in stable, web is just another device target for your app.
By leveraging the web platform’s many strengths, Flutter built a foundation for building rich interactive web applications. We primarily focused on performance and improvements to our rendering fidelity. In addition to our HTML renderer, we added a new CanvasKit-based renderer. We’ve also added web-specific features, such as a Link widget, to make sure your app running in the browser feels like a web app.
Find more details about this stable release in Flutter’s web support blog post.
Desktop
In this release, we’re pleased to announce that Flutter’s desktop support is available in the stable channel under an early release flag. What this means is that we’re ready for you to give it a try as a deployment target for your Flutter apps: you can think of it as a “beta snapshot” that previews the final stable release coming later this year.
To bring Flutter desktop to this degree of quality, there have been improvements both big and small, starting with working to ensure that text editing operates like the native experience on each of the supported platforms, including foundational features like text selection pivot points and being able to stop propagation of a keyboard event once it’s been handled. On the mouse input side, dragging with a high precision pointing device now starts immediately instead of waiting for the lag needed when handling touch input. Also, a built-in context menu has been added to the TextField and TextFormField widgets for Material and Cupertino design languages. Finally, grab handles have been added to the ReorderableListView widget.

The ReorderableListView now has grab handles for easy drag ’n’ drop with a mouse Pic courtesy: medium.com
The ReorderableListView now has grab handles for easy drag ‘n’ drop with a mouse
Pic courtesy: medium.comThe ReorderableListView was always good at moving items around with very little effort on your part as a developer, but it required the user to initiate a drag using a long-press. That made sense on a mobile device, but few desktop users would think to long-press on an item with their mouse to move it around, so this release includes a grab handle suitable for mouse or touch input. Another improvement for platform-idiomatic functionality is an updated scrollbar that shows up correctly for the desktop form-factor.

This release includes an updated Scrollbar widget that works great in a desktop environment Pic courtesy: medium.com
This release includes an updated Scrollbar widget that works great in a desktop environment
Pic courtesy: medium.comThe Scrollbar widget has been updated to provide the interactive features that are expected on the desktop, including the ability to drag the thumb, click on the track to page up and down, and to show a track when the mouse hovers over any part of the scrollbar. Furthermore, since the Scrollbar is themeable using the new ScrollbarTheme class, you can style it to match your app’s look and feel.
For additional desktop-specific functionality, this release also enables command-line argument handling for Flutter apps so that simple things like a double-click on a data file in the Windows File Explorer can be used to open the file in your app. We’ve also worked hard to make resizing much smoother for both Windows and macOS, and to enable IME (Input Method Editors) for international users.

Flutter desktop now supports intuitive IME input
Pic courtesy: medium.com
In addition, we have provided updated docs on what you need to do to begin preparing your desktop app for deployment to the appropriate OS-specific stores. Give them a try and please provide feedback if we’ve missed anything.
When it comes to trying the beta for Flutter desktop, you can access it by switching to the beta channel as expected as well as setting the config flags for the platforms you’re targeting according to the directions on flutter.dev. In addition, we’ve also made a snapshot of the beta bits available on the stable channel. If you use ‘flutter config’ to enable one of the desktop config settings (for example, enable-macos-desktop), then you can try out the beta functionality of the desktop support w/o having to go through the lengthy process of moving to the beta channel and pulling down all the latest beta of the Flutter SDK, building the tools, etc. This is great for giving it a try or using the desktop support as a simple “Flutter Emulator.”
However, if you choose to stay on the stable channel to access the desktop beta, you won’t get new features or bug fixes as quickly as switching to the beta or dev channels. So, if you’re actively targeting Windows, macOS, or Linux, we recommend switching to a channel that provides updates more quickly.
As we approach our first full production-quality release of Flutter desktop, we know we have more to do, including support for integration with native top-level menus, text editing that feels more like the experience of the individual platforms, and accessibility support, as well as general bug fixes and performance enhancements. If there are other things you think need doing before the desktop moves to production quality, please be sure to provide your feedback.
Google Mobile Ads to Beta
In addition to Flutter desktop moving to beta, today we’re excited to announce an open beta for Google Mobile Ads SDK for Flutter. This is a brand new plugin that provides inline banner and native ads, in addition to the existing overlay formats (overlay banner, interstitial, and rewarded video ads). This plugin unifies support for Ad Manager and Admob, so no matter what size publisher you are, this plugin can be tailored to your scenarios.

Pic courtesy: medium.com
We’ve been piloting this plugin with some of our early customers in a private beta program, and many of them have successfully launched their apps with these new formats. For example, Sua Musica (largest Latin American music platform for independent artists with more than 15k verified artists and 10M MAU) launched their new Flutter app with the Google Mobile Ads SDK for Flutter plugin. They saw an 350% increase on Impressions with a 43% increase on CTR and 13% increase on eCPM.
This plugin is available for you to use today. As part of Flutter Engage, Andrew Brogdon and Zoey Fan presented a session on “Monetizing apps with Flutter” (available on the Flutter Engage site), where they talk about monetization strategies for apps built with Flutter, and how you can load ads in your Flutter app. Moreover, we created a new Ads page on flutter.dev where you can find all helpful resources such as the plugin implementation guide, the inline banner and native ads codelab, and the overlay banner, interstitial and rewarded video ads codelab. Please be sure to check them out!
For more information and to develop mobile apps using Flutter, Hire Flutter Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop Mobile Apps using Flutter, please visit our technology page.
Content Source:
- medium.com
Pros and cons of React Native development in 2021
React Native, next to Flutter and PWA, was called a revolution in cross-platform app development and delivering great mobile experience.
Code repository that’s shareable between platforms? Reusable components? That definitely sounds tempting.
React Native has been praised for its “Learn once, write anything.” objective which means you get a native look and feel of your app for both iOS and Android, and you may also include platform-specific modules.
For a developer with an experience in JavaScript, and React itself, it is easy to take up React Native and start building on it right away.
Some time ago one of our React Native apps, Guild, went public. (Update: Guild has been recognized by Red Herring’s 2019 Top 100 European Startups.)
We’re extremely proud of how the app is turning out and we just can’t wait to write more of them. Our devs and some of our clients are fully aboard the React Native train and in this post, we will tell you exactly why is that: from a perspective of a business owner and a JavaScript developer. As well as some React Native advantages and limitations.
Is React Native the pick for your next app?
Build a product your users will love to use. Get a highly performant, native app for Android, iOS, and even the Web. Work with our developers and designers to squeeze the most out of your app idea and React Native.
Business Perspective on React Native
Unlike other cross-platform frameworks like Ionic, the Facebook team stresses they acknowledge the differences between different platforms and React Native reflects that. Therefore, you can still include modules specific for iOS and Android like status bars, navigation, or access to native elements like camera and contacts are built according to the platform.
Using libraries such as React Native for Web or ReactXP allows a developer to build a cross-platform app that runs on the Web too, so there’s no need to build separate apps at all. We used ReactXP in one of our projects and it really felt like we’re getting the Web version for free. That’s pretty amazing.
Note that using React Native DOES NOT mean you will not need any help from a native developer. If your app includes many different native features, some work on their side may be required.
Now, when it comes to a team building…
Your front-end web developer can actually become a mobile developer without a need of learning iOS’s Swift or Java/Kotlin for Android. With some knowledge about native UI elements, React, and some platform-specific patterns, React Native is easy to pick up. That is a game changer in terms of building a team as your app will require just one instead of two (or even three if you’re also to conquer the Web).
You can hire JS developers who will be able to deliver for all platforms. Therefore, it is much easier for them to exchange knowledge, conduct a code review, and understand the code. What a difference it makes in terms of time and cost! Not to mention that React Native is all about bringing agility of web development to cross-platform development, with native results.
About the performance…
Some may argue that nothing will surpass the performance of native apps. It may be even true, but products written with React Native are almost identical in how they perform. Sometimes even better. In his great article comparing Native iOS and RN, John Calderaio says:
"(According to) the data we collected through measuring both of the application's CPU, GPU, and Memory during the tasks in each of the four tabs, the apps are also almost identical in how they perform. (…) React Native, winning two out of three categories, comes in first place as the better performing platform."
Wrapping-up: Pros and Cons for Business
Pros:
- Time and cost efficiency
- Native look and feel of your apps
- Sharing the codebase for iOS, Android, and the Web (with ReactXP and React Native for Web)
- One team for multiple platforms
- Awesome performance
Cons:
- Need for an expertise from a native developer for some platform-specific modules
- It’s not fully cross-platform, single-codebase approach
If you’re looking for a framework that will let you build a great cross-platform mobile app, check out Flutter.

Pic courtesy: medium.com
Bloomberg is a great example of preformant app written with React Native. Image source belitsoft.com.
Developer’s Perspective on React Native
When you start working with React, typically you go with a bundler like Webpack and spend some time considering the right bundling modules for your app. React Native is different, and yet it works similarly to React. It comes with everything you need to just sit down and start writing your code.
Hot/Live reload (similar to Instant Run on Android) is a beloved, killer feature that allows a developer to see introduced changes right away without complete rebuilding of the app. You don’t have to constantly check the results of actions you take which greatly boosts productivity and saves time on compilation.
When it comes to scroll, animations, buttons, text inputs and others, React Native gives an efficient recipe that allows developers to conduct basic tasks easily. Component usage is heavily simplified in comparison to native development and it’s huge.
Adding native modules may not be a piece of cake though.
Whereas there are countless libraries to choose from for iOS and Android, React Native does not exactly shine here. The list of third-party libraries and components is quite long, but in many cases they leave a lot to be desired. When working on modules like device sensors or push notifications, there is a chance you may need some help from a native programmer.
Truth to be told, the Facebook team together with outside collaborators and thriving population of active users constantly work on React Native making it better every day with over 2500 commits from 500 contributors last year.
According to Sophie Alpert, Engineering Manager on React:
"We're working on a large-scale rearchitecture of React Native to make the framework more flexible and integrate better with native infrastructure in hybrid JavaScript/native apps."
Even if it may happen that you’ll need to hack some existing solution or write something from scratch, this will happen more and more rarely.
Wrapping-up: Pros and Cons for a Developer
Pros:
- You’re web AND mobile developer!
- Great productivity
- Easy setup
- Simplified usage of styling components
- Hot/live reloading feature
Cons:
- Need of hacking some existing solutions or creating new ones from scratch
- Documentation still needs an upgrade
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
- medium.com
Using Sanctum to authenticate a mobile app
Sanctum is Laravel’s lightweight API authentication package. This tutorial will go over using Laravel Sanctum to authenticate a mobile app. The app will be built in Flutter, Google’s cross-platform app development toolkit. We may skip some implementation details of the mobile app since that is not the focus of this tutorial.
The backend
We’ve set up Homestead to provision a domain name, api.sanctum-mobile.test, where my backend will be served, as well as a MySQL database.
First, create the Laravel app:
laravel new sanctum_mobile
At the time of writing, it gives me a new Laravel project (v8.6.0). As with the SPA tutorial, the API will provide a list of books, so We’ll create the same resources:
php artisan make:model Book -mr
The mr flags create the migration and controller too. Before we mess with the migrations, let’s first install the Sanctum package, since we’ll need its migrations again.
composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Now, create the books migration:
Schema::create('books', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('author'); $table->timestamps(); });
Next, run your app’s migrations:
php artisan migrate
If you now take a look in the database, you’ll see the Sanctum migration has created a personal_access_tokens table, which we’ll use later when authenticating the mobile app.
Let’s update DatabaseSeeder.php to give us some books (and a user for later):
Book::truncate(); $faker = \Faker\Factory::create(); for ($i = 0; $i < 50; $i++) { Book::create([ 'title' => $faker->sentence, 'author' => $faker->name, ]); } User::truncate(); User::create([ 'name' => 'Alex', 'email' => 'alex@alex.com', 'password' => Hash::make('pwdpwd'), ]);
Now seed the database: php artisan db:seed. Finally, create the route and the controller action. Add this to the routes/api.php file:
Route::get('book', [BookController::class, 'index']);
and then in the index method of BookController, return all the books:
return response()->json(Book::all());
After checking that the endpoint works — curl https://api.sanctum-mobile.test/api/book — it’s time to start the mobile app.
The mobile app
For the mobile app, we’ll be using Android Studio and Flutter. Flutter allows you to create cross-platform apps that re-use the same code for Android and iPhone devices. First, follow the instructions to install Flutter and to set up Android Studio, then launch Android Studio and click “Create a new Flutter project.”
Follow the recipe in Flutter’s cookbook to fetch data from the internet to create a page that fetches a list of books from the API. A quick and easy way to expose our API to the Android Studio device is to use Homestead’s share command:
share api.sanctum-mobile.test
The console will output an ngrok page, which will give you a URL (something like https://0c9775bd.ngrok.io) exposing your local server to the public. (An alternative to ngrok is Beyond Code’s Expose.) So let’s create a utils/constants.dart file to put that in:
const API_URL = 'http://191b43391926.ngrok.io';
Now, back to the Flutter cookbook. Create a file books.dart which will contain the classes required for our book list. First, a Book class to hold the data from the API request:
class Book { final int id; final String title; final String author; Book({this.id, this.title, this.author}); factory Book.fromJson(Map<String, dynamic> json) { return Book( id: json['id'], title: json['title'], author: json['author'], ); } }
Second, a BookList class to fetch the books and call the builder to display them:
class BookList extends StatefulWidget { @override _BookListState createState() => _BookListState(); } class _BookListState extends State<BookList> { Future<List<Book>> futureBooks; @override void initState() { super.initState(); futureBooks = fetchBooks(); } Future<List<Book>> fetchBooks() async { List<Book> books = new List<Book>(); final response = await http.get('$API_URL/api/book'); if (response.statusCode == 200) { List<dynamic> data = json.decode(response.body); for (int i = 0; i < data.length; i++) { books.add(Book.fromJson(data[i])); } return books; } else { throw Exception('Problem loading books'); } } @override Widget build(BuildContext context) { return Column( children: <Widget>[ BookListBuilder(futureBooks: futureBooks), ], ); } }
And last, a BookListBuilder to display the books:
class BookListBuilder extends StatelessWidget { const BookListBuilder({ Key key, @required this.futureBooks, }) : super(key: key); final Future<List<Book>> futureBooks; @override Widget build(BuildContext context) { return FutureBuilder<List<Book>>( future: futureBooks, builder: (context, snapshot) { if (snapshot.hasData) { return Expanded(child: ListView.builder( itemCount: snapshot.data.length, itemBuilder: (context, index) { Book book = snapshot.data[index]; return ListTile( title: Text('${book.title}'), subtitle: Text('${book.author}'), ); }, )); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } return CircularProgressIndicator(); } ); } }
Now we just need to modify the MyApp class in main.dart to load the BookList:
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Sanctum Books', home: new Scaffold( body: BookList(), ) ); } }
Now launch this in your test device or the emulator, and you should see a list of books.
Authentication with Sanctum
Great, so we know the API is working and that we can fetch books from it. The next step is to set up authentication.
We’re going to use the provider package, and follow the guidelines in the official documentation for setting up simple state management. We want to create an authentication provider that keeps track of the logged-in status and eventually communicates with the server. Create a new file, auth.dart. Here’s where the authentication functionality will go. For the moment, we’ll return true so we can test the process works:
class AuthProvider extends ChangeNotifier { bool _isAuthenticated = false; bool get isAuthenticated => _isAuthenticated; Future<bool> login(String email, String password) async { print('logging in with email $email and password $password'); _isAuthenticated = true; notifyListeners(); return true; } }
With this provider, we can now check whether we’re authenticated and display the correct page accordingly. Modify you main function to include the provider:
void main() { runApp( ChangeNotifierProvider( create: (BuildContext context) => AuthProvider(), child: MyApp(), ) ); }
… and modify the MyApp class to show the BookList widget if we’re logged-in, or a LoginForm widget otherwise:
body: Center( child: Consumer<AuthProvider>( builder: (context, auth, child) { switch (auth.isAuthenticated) { case true: return BookList(); default: return LoginForm(); } }, ) ),
The LoginForm classes contain a lot of “widgety” cruft, so We’ll refer you to the GitHub repo if you’re interested in looking at it. Anyway, if you load the app in your test device, you should see a login form. Fill in a random email and password, submit the form, and you’ll see a list of books.
Ok, let’s set up the backend to handle the authentication. The docs tell us to create a route that will accept the username and password, as well as a device name, and return a token. So let’s create a route in the api.php file:
Route::post('token', [AuthController::class, 'requestToken']);
and a controller: php artisan make:controller AuthController. This will contain the code from the docs:
public function requestToken(Request $request): string { $request->validate([ 'email' => 'required|email', 'password' => 'required', 'device_name' => 'required', ]); $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } return $user->createToken($request->device_name)->plainTextToken; }
Providing the username and password are valid, this will create a token, save it in the database, and return it to the client. To get this to work, we need to add the HasApiTokens trait to our User model. This gives us a tokens relationship, allowing us to create and fetch tokens for the user, and a createToken method. The token itself is a sha256 hash of a 40-character random string: this string (unhashed) is returned to the client, which should save it to use with any future requests to the API. More precisely, the string returned to the client is composed of the token’s id, followed by a pipe character (|), followed by the plain text (unhashed) token.
So now we have this endpoint in place, let’s update the app to use it. The login method will now have to post the email, password, and device_name to this endpoint, and if it gets a 200 response, save the token in the device’s storage. For device_name, We’re using the device_info package to get the device’s unique ID, but in fact, this string is arbitrary.
final response = await http.post('$API_URL/token', body: { 'email': email, 'password': password, 'device_name': await getDeviceId(), }, headers: { 'Accept': 'application/json', }); if (response.statusCode == 200) { String token = response.body; await saveToken(token); _isAuthenticated = true; notifyListeners(); }
We use the shared_preferences package, which allows for the storage of simple key-value pairs, to save the token:
saveToken(String token) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString('token', token); }
So now we’ve got the app displaying the books page after a successful login. But of course, as things stand, the books are accessible with or without successful login. Try it out: curl https://api.sanctum-mobile.test/api/book. So now let’s protect the route:
Route:::middleware('auth:sanctum')->get('book', [BookController::class, 'index']);
Login again via the app, and this time you’ll get an error: “Problem loading books”. You are successfully authenticating, but because we don’t as yet send the API token with our request to fetch the books, the API is quite rightly not sending them. As in the previous tutorial, let’s look at the Sanctum guard to see what it’s doing here:
if ($token = $request->bearerToken()) { $model = Sanctum::$personalAccessTokenModel; $accessToken = $model::findToken($token); if (! $accessToken || ($this->expiration && $accessToken->created_at->lte(now()->subMinutes($this->expiration))) || ! $this->hasValidProvider($accessToken->tokenable)) { return; } return $this->supportsTokens($accessToken->tokenable) ? $accessToken->tokenable->withAccessToken( tap($accessToken->forceFill(['last_used_at' => now()]))->save() ) : null; }
The first condition is skipped since we aren’t using the web guard. Which leaves us with the above code. First, it only runs if the request has a “Bearer” token, i.e. if it contains an Authorization header which starts with the string “Bearer”. If it does, it will call the findToken method on the PersonalAccessToken model:
if (strpos($token, '|') === false) { return static::where('token', hash('sha256', $token))->first(); } [$id, $token] = explode('|', $token, 2); if ($instance = static::find($id)) { return hash_equals($instance->token, hash('sha256', $token)) ? $instance : null; }
The first conditional checks to see whether the pipe character is in the token and, if not, to return the first model that matches the token. We assume this is to preserve backward compatibility with versions of Sanctum before 2.3, which did not include the pipe character in the plain text token when returning it to the user. (Here is the pull request: the reason was to make the token lookup query more performant.) Anyway, assuming the pipe character is there, Sanctum grabs the model’s ID and the token itself, and checks to see if the hash matches with what is stored in the database. If it does, the model is returned.
Back in Guard: if no token is returned, or if we’re considering expiring tokens (which we’re not in this case), return null (in which case authentication fails). Finally:
return $this->supportsTokens($accessToken->tokenable) ? $accessToken->tokenable->withAccessToken( tap($accessToken->forceFill(['last_used_at' => now()]))->save() ) : null;
Check that the tokenable model (i.e., the User model) supports tokens (in other words, that it uses the HasApiTokens trait). If not, return null – authentication fails. If so, then return this:
$accessToken->tokenable->withAccessToken( tap($accessToken->forceFill(['last_used_at' => now()]))->save() )
The above example uses the single-argument version of the tap helper. This can be used to force an Eloquent method (in this case, save) to return the model itself. Here the access token model’s last_used_at timestamp is updated. The saved model is then passed as an argument to the User model’s withAccessToken method (which it gets from the HasApiTokens trait). This is a compact way of updating the token’s last_used_at timestamp and returning its associated User model. Which means authentication has been successful.
So, back to the app. With this authentication in place, we need to update the app’s call to the book endpoint to pass the token in the request’s Authorization header. To do this, update the fetchBooks method to grab the token from the Auth provider, then add it to the header:
String token = await Provider.of<AuthProvider>(context, listen: false).getToken(); final response = await http.get('$API_URL/book', headers: { 'Authorization': 'Bearer $token', });
Don’t forget to add a getToken method to the AuthProvider class:
Future<String> getToken() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString('token'); }
Now try logging in again, and this time the books should be displayed.
For more information and to develop web application using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
- laravel-news.com