29,99 €
Flutter’s rapid adoption by developers and businesses alike has led to an increased demand for skilled developers who can deliver high-quality Flutter apps. Flutter can be a great tool to develop apps for yourself, but you don’t always need to consider things like scalability or business goals as a hobbyist. When you build apps for a business, however, you must use specific tools to help the business achieve its goals. This requires solutions to be fast, reliable, and delivered on time. This book will help you meet these business requirements.
You'll begin by learning how to build responsive UIs that work on all devices. Next, you'll delve into state management, understanding how to select the appropriate solution and gaining hands-on experience with InheritedWidget, ChangeNotifier, and BLoC. Later, you'll move on to high-level practices such as layered architecture, dependency injection, and repository patterns. The book will also show you how to develop features of any complexity, such as multithreading and native layer implementations. You'll also learn how to ensure the quality of your solutions by prioritizing testing.
By the end of this book, you'll be able to deliver well-architected Flutter projects that are stable, scalable, and maintainable.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 443
Veröffentlichungsjahr: 2024
Flutter Design Patterns and Best Practices
Build scalable, maintainable, and production-ready apps using effective architectural principles
Daria Orlova
Esra Kadah
Jaime Blasco
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Kaustubh Manglurkar
Book Project Manager: Sonam Pandey
Senior Editor: David Sugarman
Technical Editor: K Bimala Singha
Copy Editor: Safis Editing
Proofreader: David Sugarman
Indexer: Pratik Shirodkar
Production Designer: Vijay Kamble
DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey
Publication date: September 2024
Production reference: 1060924
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-80107-264-9
www.packtpub.com
To the memory of my grandmothers, Frosya and Ira, who were my guiding stars during their time and even more so after. To my husband, Alex, for his infinite support in everything I do. To my little brother, Matvey, who inspires me to be my best. And to my parents, Sergey and Tatyana, for raising me to be the person I am today.
– Daria Orlova
To my beloved parents, Emine and Erdinc, who have been the foundation of my journey, always striving to provide the best for me and grounding me with their dedicated support.
To my dear sisters, Ceren and Neslihan, and my brother, Enes, whose encouragement and companionship have guided me through good times and bad. Your patience, countless hours of listening, and unwavering support have profoundly influenced every decision I have made.
To my amazing professors, Gurkan Ozturk and Emre Cimen from Eskisehir Technical University, who introduced me to coding and consistently supported and motivated me. Your guidance made sure I never felt alone as I started on this path, planting the seeds for my future success.
– Esra Kadah
Dedicated to the memory of my father, whose love was my constant source of strength. Your belief in me knew no bounds, and I am eternally grateful for your support.
– Jaime Blasco
Daria Orlova is a mobile app specialist, who started with native Android in 2015 and discovered Flutter in 2019. She is the co-founder of BBapps, creating “apps that care for you and the planet.” Previously, at Chili Labs, the top mobile agency in the Baltics, together with the team, she delivered 50+ projects, winning awards including RedDot and W3. Daria is an active community member – a Google Developer Expert (GDE) in Flutter and Dart, Flutterista, and WTM ambassador, mentor, technical writer, and public speaker who is passionate about quality tech education. She holds a B.Sc. in computer science.
I want to thank my friends, Anna Leushchenko, Cagatay Ulusoy, Dmitry Zhifarsky, and Tair Rzayev, whose expertise has greatly helped to make this book better. Thank you to Packt and tech reviewer Ahmed Fathy for making this book happen, and to Chili Labs, for providing the experience that was put into the foundation of this book.
Esra Kadah is a senior app developer specializing in Flutter, with a passion for integrating programming, UI/UX design, and psychology. She enjoys building and contributing to thriving communities. She is a co-organizer of Flutteristas, Flutter Berlin, and CMX Istanbul, and serves as a Women Techmakers Ambassador. She has delivered over 60 talks, organized more than 150 events, and hosted 40+ streams, collaborating with Google Developer Groups, Google Developer Student Clubs, the Flutter community, Flutteristas, and Women Techmakers.
Jaime Blasco is a seasoned Flutter developer with a deep-rooted passion for crafting exceptional mobile experiences. As a Google Developer Expert (GDE) in Flutter, he possesses an in-depth understanding of the framework and its capabilities. His active involvement in the Flutter community, notably as a co-leader of the Spanish Flutter community, underscores his commitment to knowledge sharing and collaboration. He currently develops the Hypervolt app, a Flutter-based solution that seamlessly connects users to EV chargers. Jaime ensures smooth user interactions and efficient hardware communication, delivering a reliable charging experience.
Ahmed Fathy is a skilled senior software engineer from Alexandria, Egypt. He holds a B.Sc. in computer and systems engineering from Al-Azhar University. Specializing in Flutter development, he has extensive experience as an instructor with private training companies and his own online courses and in projects held by Egyptian ministries of communication.
Ahmed has developed numerous mobile applications. He is a community leader at GDG Alexandria and a previous co-founder of Google DSC Al-Azhar. Ahmed is passionate about civil work, community building, and sharing knowledge.
Messaging friends, booking airplane tickets, ordering a grocery delivery, checking bank accounts, buying metro tickets... this is just a short list of tasks we accomplish today with the help of mobile and web applications. Apps are omnipresent, and someone must develop them. If you are holding this book, there is a high chance that you are one of these developers.
In recent years, Flutter has become a stable and widely used framework for building apps. And not just mobile apps, as it also supports building for web, desktop, and beyond. However, to thrive in the modern world, apps need to be more than just functional – they must be beautiful, fast, and reliable. These qualities are achieved through the approaches used to build the apps. A scalable, flexible, maintainable, and testable architecture is essential to help businesses stand out and to provide users with the high-quality experience they expect. This is where design patterns and best practices come into play.
Design patterns are proven blueprints for solutions to common problems that arise in software design. They provide standard terminology and are specific to particular scenarios, making the development process more efficient and reliable. For instance, patterns such as Singleton, Observer, and Factory Method offer templates for solving issues related to object creation, communication between objects, and more.
Best practices, on the other hand, are guidelines or methodologies that have been shown through experience and research to lead to optimal results. These practices include coding standards, architectural principles, and development processes that ensure high-quality software. They help to maintain code readability, performance, security, and scalability.
This book dives into the details of Flutter’s inner workings, teaches various design patterns to build Flutter apps, and explores the best practices for developing robust applications. Understanding these fundamentals is crucial for making informed decisions about which practices and guidelines to follow and which to adapt or skip.
This knowledge is built on the experience of developing over 50 apps of various scales in industry-leading mobile development agencies and companies. However, it’s important to remember that there is always room for individual opinions and adjustments.
It is a great time to be a Flutter developer, and this book will help you become one who is highly skilled and competitive.
Mobile developers of any level can gain practical insights into how to craft Flutter apps according to best practices. You are especially likely to benefit from this book if you belong to one of the following groups:
Flutter developers: If you have already built some projects with Flutter and want to enhance your skills to build scalable, maintainable, and stable applications that follow the best practices, this book will show you how.Mobile developers from other tech stacks: If you have already built mobile apps in other frameworks, such as React Native or Xamarin, or for native platforms, and want to transition to Flutter, this book will teach you how to apply your existing knowledge to Flutter.Aspiring Flutter developers: If you have not yet built apps in any tech stacks but have some programming experience in other stacks, this book can be used to navigate the Flutter framework alongside more beginner-friendly resources.Chapter 1, Best Practices for Building UIs with Flutter, discusses the difference between imperative and declarative approaches to UI building and why modern frameworks prefer the latter. We will explore the details of the Flutter widget tree system, and practical advice on how to build performant interfaces.
Chapter 2, Responsive UI for All Devices, provides an overview of the Flutter layout algorithm, dives into the best practices and available options for building responsive interfaces, and covers accessibility best practices.
Chapter 3, Vanilla State Management, opens the topic of state management in Flutter. It provides the definition of state and its different types. In this chapter, we start building the Candy Store app, which we will continue building throughout the book, and learn how to implement state management patterns in the vanilla Flutter way. You will also see an overview of the InheritedWidget class details, and practical tips on working with BuildContextin Flutter.
Chapter 4, State Management Patterns and Their Implementations, continues the topic of state management, introducing popular industry patterns such as MVVM and MVI, the rationale behind using them, and their implementation in Flutter with and without third-party libraries.
Chapter 5, Creating Consistent Navigation, provides an overview of navigation patterns in Flutter, going into details on how to implement imperative style navigation and declarative style navigation. We will see some examples of building complex navigation scenarios and when to choose which approach.
Chapter 6, The Responsible Repository Pattern, introduces the Repository pattern and its benefits for scalable app architecture. The chapter goes deep into implementation details and explores practices for building flexible data sources.
Chapter 7, Implementing the Inversion of Control Principle, explores various approaches to implementing the Inversion of Control principle, via practices such as dependency injection and the Service Locator pattern, and demonstrates their practical application with the help of different libraries.
Chapter 8, Ensuring Scalability and Maintainability with Layered Architecture, provides an overview of how to structure the code that we have built up to this point according to layered architecture principles. The chapter also highlights how we have been following the SOLID and other best software design principles all along.
Chapter 9, Mastering Concurrent Programming in Dart, introduces concepts related to concurrent programming in general and provides an overview of asynchronous APIs in Dart. The chapter goes into details of how to work efficiently with the Future APIs, as well as how to handle parallel operations with the Isolates API.
Chapter 10, A Bridge to the Native Side of Development, provides an overview of the Flutter app architecture from the perspective of the SDK and hosting platforms. The chapter goes into details of working with platform channels, a mechanism used to communicate with the host platform, as well as demonstrating the shortcomings of this API. We then explore a type-safe way to implement that communication via the pigeon code generation library.
Chapter 11, Unit Tests, Widget Tests, and Mocking Dependencies, provides an overview of the automated testing approaches in Flutter. You will learn how to write unit tests and go into the details of widget testing. The chapter showcases the mocking dependencies technique and how to implement it with the Mockito library.
Chapter 12, Static Code Analysis and Debugging Tools, discusses the topic of static analysis in Flutter and why it’s important to establish coding conventions and follow them consistently. We then see how this can be automated by setting up a robust static analysis system. The chapter also explores debugging practices and their applications, such as logging, assertions, breakpoints, and Flutter DevTools.
You will need to download an IDE that supports development with Flutter and Dart, and the Flutter SDK itself.
Software covered in the book
Operating system requirements
Flutter SDK 3.22.0+
Windows, macOS, Linux,or ChromeOS
Dart 3.4.0+
Windows, macOS, Linux,or ChromeOS
You may use any IDE of your choice, but some popular ones that support Flutter are Android Studio, VS Code, and IntelliJ IDEA. Up-to-date details for installation can always be viewed at the official website: https://docs.flutter.dev/get-started/install.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
The best way to read this book is consecutively, chapter by chapter, as we start with the basics and build on top of the previous chapter with every step. That said, you may still find individual chapters useful if you’re searching for specific topics – just remember they are part of the bigger project.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Flutter-Design-Patterns-and-Best-Practices. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Here’s how we could use the Align widget to achieve the same effect.”
A block of code is set as follows:
Container( constraints: BoxConstraints.tight( const Size(200, 100), ), color: Colors.red, child: const Text('Hello World'), );When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Container( alignment: Alignment.center, constraints: BoxConstraints.tight( const Size(200, 100), ), color: Colors.red, child: const Text('Hello World'), );Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Select System info from the Administration panel.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve read Flutter Design Patterns and Best Practices, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781801072649
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyIn this part, you will learn how to build beautiful user interfaces (UIs) with Flutter and how to do that in a productive and efficient manner. The topics that we will cover include the difference between imperative and declarative UI paradigms, the details of the inner workings of the most important concept in Flutter – widgets, best practices for working with widgets and their lifecycle, the Flutter layout algorithm, and various techniques for building responsive and accessible UIs.
This part includes the following chapters:
Chapter 1, Best Practices for Building UIs with FlutterChapter 2, Responsive UIs for All Devices