Flutter For Dummies book cover

Flutter For Dummies

By: Barry Burd Published: 08-04-2020

Create awesome iOS and Android apps with a single tool!  

Flutter is an app developer’s dream come true. With Google’s open source toolkit, you can easily build beautiful apps that work across platforms using a single codebase. This flexibility allows you to get your work out to the widest possible audience. With Flutter already being used by thousands of developers worldwide in a market where billions of apps are downloaded every year, now is the right time to get ahead of the curve with this incredible tool.  

Flutter for Dummies is your friendly, ground-up route to creating multi-platform apps.       

From how to construct your initial frameworks to writing code in Dart, you’ll find the essentials you need to ride the Flutter revolutionary wave to success. This book includes how to create an intuitive and stunning UI, add rich interactivity, and easily pull in data. You’ll also see how Flutter features like Hot Reload—providing sub-second refreshes as you refine your work—help you make sure your app is a delight to use. 

  • Start simple: follow steps to build a basic app 
  • It’s alive! Keep connected to online data 
  • It moves! Make things fun with animated features 
  • Get the word out: use tips to expand your audience  

Whether you’re a fledgling developer or an expert wanting to add a slick feather to your programming cap, join the Flutter revolution now and soar above the rest! 

Articles From Flutter For Dummies

page 1
page 2
11 results
11 results
Flutter For Dummies Cheat Sheet

Cheat Sheet / Updated 02-14-2022

Flutter's online documentation is a great source of information, but sometimes you'd rather glance quickly at an example. This cheat sheet has some sample code. Just grab it and go!

View Cheat Sheet
Setting Device Orientation in Your Flutter App

Article / Updated 07-29-2020

How big is the device you’ll be running your Flutter app on? The answer is "You don't know." You can run a Flutter app on a small iPhone 6, or in a web page on a 50-inch screen. You want your app to look good no matter what size the device happens to be. How can you do that? The Dart code below has the answer Checking Device Orientation in a Flutter App // App0613.dart import 'package:flutter/material.dart'; import 'App06Main.dart'; Widget buildColumn(context) { if (MediaQuery.of(context).orientation == Orientation.landscape) { return _buildOneLargeRow(); } else { return _buildTwoSmallRows(); } } Widget _buildOneLargeRow() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ buildRoundedBox("Aardvark"), buildRoundedBox("Baboon"), buildRoundedBox("Unicorn"), buildRoundedBox("Eel"), buildRoundedBox("Emu"), buildRoundedBox("Platypus"), ], ), ], ); } Widget _buildTwoSmallRows() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ buildRoundedBox("Aardvark"), buildRoundedBox("Baboon"), buildRoundedBox("Unicorn"), ], ), SizedBox( height: 30.0, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ buildRoundedBox("Eel"), buildRoundedBox("Emu"), buildRoundedBox("Platypus"), ], ), ], ); } The following images show what happens when you run the Dart code above. When the device is in portrait mode, you see two rows, with three boxes on each row. But when the device is in landscape mode, you see only one row, with six boxes. Here's the portrait option. And the landscape mode. The difference comes about because of the if statement in the above Dart code. if (MediaQuery.of(context).orientation == Orientation.landscape) { return _buildOneLargeRow(); } else { return _buildTwoSmallRows(); } Yes, the Dart programming language has an if statement. It works the same way that if statements work in other programming languages. if (a certain condition is true) { Do this stuff; } otherwise { Do this other stuff; } In the name MediaQuery, the word Media refers to the screen that runs your Flutter app. When you call MediaQuery.of(context), you get back a treasure trove of information about that screen, such as orientation: Whether the device is in portrait mode or landscape mode height and size.width: The number of dp units from top to bottom and across the device's screen longestSide and size.shortestSide: The larger and smaller screen size values, regardless of which is the height and which is the width aspectRatio: The screen's width divided by its height devicePixelRatio: The number of physical pixels for each dp unit padding, viewInsets, and viewPadding: The parts of the display that aren't available to the Flutter app developer, such as the parts covered up by the phone's notch or (at times) the soft keyboard alwaysUse24HourFormat: The device's time display setting platformBrightness: The device's current brightness setting . . . and many more For example, a Pixel C tablet with 2560-by-1800 dp is big enough to display a row of six animal boxes in either portrait or landscape mode. To prepare for your app to run on such a device, you may not want to rely on the device's orientation property. In that case, you can replace the condition in the code above with something like the following: if (MediaQuery.of(context).size.width >= 500.0) { return _buildOneLargeRow(); } else { return _buildTwoSmallRows(); } Notice the word context in the code MediaQuery.of(context). In order to query media, Flutter has to know the context in which the app is running. That's why, _MyHomePage class's build method has a BuildContext context parameter. Want to learn more tricks? Avoid these ten mistakes when programming your Flutter app.

View Article
Using Android Studio to Develop Flutter Apps

Article / Updated 07-28-2020

Android Studio is a customized version of IntelliJ IDEA — a general-purpose IDE with tools for Java development, C/C++ development, PHP development, modeling, project management, testing, debugging, and much more. Here, you get an overview of Android Studio's main window. The focus here is on the most useful features that help you build Flutter apps, but keep in mind that Android Studio has hundreds of features and many ways to access each feature. Starting up Android Studio Each Flutter app belongs to a project. You can have dozens of projects on your computer's hard drive. When you run Android Studio, each of your projects is either open or closed. An open project appears in a window (its own window) on your computer screen. A closed project doesn't appear in a window. Several of your projects can be open at the same time. You can switch between projects by moving from window to window. Here, an open project's window is often referred to as Android Studio's main window. This can be slightly misleading because, with several projects open at a time, you have several main windows open at a time. In a way, none of these windows is more “main” than the others. When you see the term main window here, it’s a reference to the window whose Flutter project you're working on at that moment. If Android Studio is running and no projects are open, Android Studio displays its Welcome screen. The Welcome screen may display some recently closed projects. If so, you can open a project by clicking its name on the Welcome screen. For an existing app that's not on the Recent Projects list, you can click the Welcome screen's Open an Existing Android Studio Project option. If you have any open projects, Android Studio doesn't display the Welcome screen. In that case, you can open another project by choosing File→Open or File→Open Recent in an open project's window. To close a project, you can choose File→Close Project, or you can do whatever you normally do to close one of the windows on your computer. (On a PC, click the X in the window's upper right corner. On a Mac, click the little red button in the window's upper left corner.) Android Studio remembers which projects were open from one run to the next. If any projects are open when you quit Android Studio, those projects open again (with their main windows showing) the next time you launch Android Studio. You can override this behavior (so that only the Welcome screen appears each time you launch Android Studio). In Android Studio on a Windows computer, start by choosing File→Settings→Appearance and Behavior→System Settings. In Android Studio on a Mac, choose Android Studio→Preferences→Appearance and Behavior→System Settings. In either case, uncheck the Reopen Last Project on Startup check box. Android Studio’s main window Android Studio's main window is divided into several areas. Some of these areas can appear and disappear on your command. What comes next is a description of the areas you see below, moving from the top of the main window to the bottom. The areas that you see on your computer screen may be different from the areas you see above Usually, that's okay. You can make areas come and go by choosing certain menu options, including the View option on Android Studio's main menu bar. You can also click the little tool buttons on the edges of the main window. The top of the main window in Android Studio The topmost area of Android Studio contains the toolbar and the navigation bar. The toolbar contains action buttons, such as Open and Save All. It also contains the Target Selector and the Run icon. The Target Selector is the dropdown list whose default option is . In the image above, the Target Selector displays the name iPhone XR. The Run icon is the thing that looks like a green Play button. The navigation bar displays the path to one of the files in your Flutter project. A Flutter project contains many files, and, at any particular moment, you work on one of these files. The navigation bar points to that file. The Project tool window in Android Studio Below the main menu and the toolbars, you see two different areas. The area on the left contains the Project tool window, which you use to navigate from one file to another within your Android app. At any given moment, the Project tool window displays one of several possible views. For example, in the image above, the Project tool window displays its Project view. In the image below, the drop-down list was clicked and Packages view selected (instead of Project view). Packages view displays many of the same files as Project view, but in Packages view, the files are grouped differently. When you get started with Flutter app development, the Project tool window is in its default view; namely, Project view. If Android Studio doesn't display the Project tool window, look for the Project tool button — the little button displaying the word Project on the left edge of the main window. Click that Project tool button. (But wait! What if you can't find the little Project button? In that case, go to Android Studio's main menu and select Window→Restore Default Layout.) The Editor area in Android Studio The area to the right of the Project tool window is the Editor area. When you edit a Dart program file, the editor displays the file's text. You can type, cut, copy, and paste text as you would in other text editors. The Editor area can have several tabs. Each tab contains a file that's open for editing. To open a file for editing, double-click the file's branch in the Project tool window. To close the file, click the little x next to the file's name on the Editor tab. The lower area in Android Studio Below the Project tool window and the Editor area is another area that contains several tool windows. When you're not using any of these tool windows, you might not see this lower area. In the lower area, the tool window that’s often used in the Flutter app development process is the Run tool window. The Run tool window appears automatically when you click the Run icon. This tool window displays information about the run of a Flutter app. If your app isn't running correctly, the Run tool window may contain useful diagnostic information. You can force other tool windows to appear in the lower area by clicking tool buttons near the bottom of the Android Studio window. For example, when you click the Terminal tool button, Android Studio displays the Windows Command Prompt, the Mac Terminal app, or another text-based command screen that you specify. A particular tool button might not appear when there's nothing you can do with it. For example, the Run tool button might not appear until you press the Run icon. Don't worry about that. The tool button shows up whenever you need it. The status bar The status bar is at the bottom of Android Studio's window. The status bar tells you what's happening now. For example, if the cursor is on the 37th character of the 11th line in the editor, you see 11:37 somewhere on the status line. When you tell Android Studio to run your app, the status bar contains the Run tool window's most recent message. The kitchen sink In addition to the areas described above, other areas might pop up as the need arises. You can dismiss an area by clicking the area's Hide icon. Ready to give it a try? Use this guide to learn how to run your first Flutter app in Android Studio.

View Article
Flutter Animation: Making Size and Color Changes

Article / Updated 07-27-2020

With Flutter's Animation class, you're not restricted to moving things. You can control the change of any value you think needs changing. The example you find here illustrates how to make changes to an icon's size and color in Flutter. Changing a Few Flutter Animation Values // App0904.dart import 'package:flutter/material.dart'; import 'App09Main.dart'; extension MyHomePageStateExtension on MyHomePageState { Animation getAnimation(AnimationController controller) { return Tween(begin: 50.0, end: 250.0).animate(controller) ..addListener(() { setState(() {}); }); } Widget buildPositionedWidget() { int intValue = animation.value.toInt(); return Center( child: Icon( Icons.child_care, size: animation.value, color: Color.fromRGBO( intValue, 0, 255 - intValue, 1.0, ), ), ); } } When the above Flutter app starts running, a small, blue-colored baby face appears on the screen. When the user presses Forward, the baby face grows and turns color from blue to red. The icon in the code above has two properties whose values can change. The size property changes along with value. The icon grows from 50.0 dps to 250.0 dps. As the animation progresses, the color property's redness shrinks and its blueness grows. If you have experience developing Flutter apps, you may be familiar with Flutter's Color.fromRGBO constructor. The constructor's parameters are int values representing amounts of red, green, and blue and a double value that represents opacity. In the code above, the amount of red increases from 50 to 250, and the amount of blue decreases from 205 to 5. The moral of this article is, an Animation instance's value can mean anything you want it to mean. In the code you find here, the animation's value controls an icon's size and color. What value would you like to animate? Rotation? Sound volume? Speed? Curvature? Shadow? Background color? Border shape? Mood? The price of a For Dummies book? Be creative. Want to get better at developing Flutter apps? Avoid these ten mistakes.

View Article
Running Your First Flutter App in Android Studio

Article / Updated 07-27-2020

Many app developers use Android Studio to build their Flutter apps. If you’re new to Flutter and Android’s SDK, use this guide to run your first Flutter app. Before you can get going, you need to install Android Studio and add Android Studio’s Flutter plugin. Then, restart Android Studio. Now you're staring at Android Studio's Welcome screen. What do you do next? Connect to the Internet. During the run of your very first Flutter app, Android Studio downloads some additional software. Select the Start a New Flutter Project option. On your phone, an app is an app and that's all there is to it. But on your development computer, all your work is divided into projects. For professional purposes, you're not absolutely correct if you think of one app as equaling one project. If you don't see the Start a New Flutter Project option, you may not have installed the Flutter plugin correctly. Having selected Start a New Flutter Project, you'll see three dialog boxes, one after another. The first asks what kind of Flutter project you want to create, the second asks for the new app's name and other details, and the third creates something called a package. In the first dialog box, select Flutter Application and then click Next. The second dialog box has four fields: Project Name, Flutter SDK Path, Project Location, and Description. Select a name that has only lowercase letters and, if you want, underscore (_) characters. Flutter project names cannot contain uppercase letters, blank spaces, or punctuation characters other than the underscore. If you create many Flutter apps, keeping track of them all can drive you crazy. So, it helps if you decide on a formula for naming your apps and then stick to that formula as closely as you can. Later on, when you start marketing your apps, you can abandon the formula and use clever names that attract peoples' attention. For the Flutter SDK path, supply your Flutter SDK path. If you can’t find it, search your hard drive for a folder named flutter. It's bound to be there somewhere. Don't change the Project Location option, unless you have a specific reason for doing so. You don't have to specify a new directory for each of your projects. Android Studio does that for you automatically with this project location as the starting point. For the description, type something that's silly and off the wall. Do it now, while you still can. When you create apps professionally, you have to be more serious. After you click Next, Android Studio displays its Set the Package Name dialog box. If your company has a domain name, or if you have your own domain name, type it in the Company Domain field. If not, type anything at all or leave the default text alone. A package is a collection of closely related pieces of code, and each Flutter app belongs to its own package. In the Flutter world, it's customary to start a package's name with the reverse of a domain name. So, when you create a Flutter app, the app is usually in a package named com.domainname.somethingorother. The somethingorother part is unique to each of your apps. When you create your first project, the Company Name field's default text is probably example.com. Several years ago, the Internet Corporation for Assigned Names and Numbers (ICANN) set this name aside for anyone to use. Immediately below that, the dialog box supplies the package name example.com.whateveryounamedyourapp. This default package name is just fine when you're creating your very first Flutter apps. This dialog box may have check boxes labeled Generate Sample Content, Include Kotlin Support for Android Code, and Include Swift Support for iOS Code. Don't worry about these check boxes. Check them or don't check them. For your first Flutter app, it doesn't matter. Click Finish. As if by magic, Android Studio's main window appears. The main window has all the tools you need for developing top-notch Flutter applications. It even has a sample starter application, which you run in the next few steps. Android Studio's main window may look overwhelming at first. Notice two important items near the top of Android Studio's main window below: The Target Selector displays the text . The Run icon is a little right-pointing green arrow. What you do next depends on your development computer and your development goals. If you have a Mac and you want to run an iPhone simulator, select Open iOS Simulator in the Target Selector drop-down list. If you don't have a Mac, or if you want to run an Android emulator, select Tools→AVD Manager on Android Studio's main menu bar. In the resulting dialog box, look for a Green Arrow icon on the right side of the dialog box. Click that Green Arrow icon. If the AVD manager is empty — that is to say, if it's not like the manager shown above, which shows a virtual device labeled Pixel API 28 —you have to create an Android Virtual Device. Android Virtual Devices don't always start quickly. On a computer with 16 gigabytes of RAM, the start-up time may be two to three minutes. On a computer with only 4 gigabytes of RAM, the AVD might never start up. Apple's iPhone simulator tends to be a bit snappier, but you never know. When your virtual device's home screen appears on the screen, you're ready to run the sample Flutter app. Click the Run icon on Android Studio's toolbar. As a result, Android Studio's Run tool window appears in the lower portion of the main window. A few messages appear while you wait impatiently for the app to start running. When the app starts running, the virtual device (the simulator or emulator) sports a handsome display. Congratulations! Your first Flutter app is running. You can try out the app by clicking the mouse on the app's floating action button (the circular item in the lower right corner of the virtual device's screen). The message in the middle tells you how many times you've clicked the button. It's not the world's most useful Flutter app, but it's a good start. Ready to learn more? Check out our Flutter Cheat Sheet.

View Article
10 Ways to Enhance Your App Development Career

Article / Updated 07-22-2020

People who are truly good at their jobs are always looking to get better at their craft. Aspiring app developers and programmers often seek career advice: "What should I do next? How can I find a job? How can I prepare for work in the software industry?" Here, you learn some of the best hints for succeeding in app development. Practice! Practice! Practice makes app development perfection Write as much code as you can, even as a novice in the field. Find problems on the web or make up problems that interest you. If you get stuck on a problem, look for help on developer forums or set the problem aside for a while. When you've finished solving a problem, look for ways to add features to your solution. The more practice you have writing programs, the better your developer skills will be. Critique your own code Don't be satisfied with code that merely works. Good code does more than that. Good code is readable and maintainable. Good code complies with published style guidelines. Good code runs efficiently. No matter what kind of code you write, there's always room for improvement. Have other app developers review your code Other developers can find flaws that you're too entrenched in the code to notice. Expect reviewers to be critical but respectful. Respond to reviews with an open mind. Think carefully about each comment and decide whether the suggestion makes sense to you. Find out which app development technologies your nearby companies use If local companies use MySQL, learn something about MySQL. If local companies program in Haskell, learn something about Haskell. What's trendy throughout the industry may have little demand in the town where you live. Attend programming user group meetings When you hang out with programming professionals, three very nice things happen. You learn about things that you might not discover on your own. As a novice at a user group meeting, you don't choose the topic. That's a good thing because it exposes you to ideas on the periphery of your range of knowledge. You find out what issues are at the forefront of today's technology. A few years ago, the word microservices was presented at a small session in New York City. A bit of research yielded several blog posts calling microservices "the next big thing." The blog posts were right. You network with professionals in your chosen field. Who knows? Maybe one of them can help you find work! When you attend a meeting with programmers and listen to the discussion, you may not understand what people are saying. That's okay. If nothing else, you're learning by osmosis. Ask questions In college classes, students apologize for asking what they think are stupid questions. "Don't apologize," one professor says. "The stupid questions are the ones I’m sure I can answer." Ask yourself whether you truly understand app development concepts Sometimes, app developers ignore a gap as they try to grasp a particular concept. Maybe they’re either too busy, too embarrassed, or too lazy to stop and think in-depth about the concept. Eventually, that lack of understanding will come back to haunt you. Even if it doesn't, you may carry around the nagging feeling that you don’t fully understand what you’re working with. If you don't understand something that's useful for you to know, stop and try to figure it out. The effort always pays off. Learn things that you may never need to know in your app development career You may never need to run 13 miles, but you sign up for a half-marathon anyway. You may never need to paint a stunning landscape, but you visit art museums anyway. Exercise your mind. Nothing you learn ever goes to waste. Do what you love to do If you love your work, you love your life. You may need to earn money in a job you don't enjoy. If so, make a mental note to yourself: "For now, I’ll do what I have to do to support myself and my family. When I can, I’ll find work that I look forward to every day." Get plenty of sleep to be a better app developer Sleep is necessary to do your best work. That extra hour you spend trying to be an overachiever won't help you when you're too tired to think clearly. To misquote Ben Franklin: "Early to bed and late to rise puts a sparkle in your eyes."

View Article
What You Need to Program Flutter Apps: Installing the Necessary Software

Article / Updated 07-17-2020

Ready to program some Flutter apps? The first steps are an old, familiar refrain. First you get some software. Then you run the software. This is how you get your software set up to start programming Flutter apps. Getting and installing the stuff you need to program Flutter apps Download this file containing all the Flutter program examples from Dummies.com. The downloaded file is a .zip archive file. Most web browsers save files to the Downloads directory on the computer's hard drive. But your browser may be configured a bit differently. One way or another, make note of the folder containing the downloaded file FlutterForDummies_Listings.zip. Extract the contents of the downloaded file to a place on your computer's hard drive. Visit Flutter's Install Page and download the Flutter SDK. Choose a version of the software that matches your operating system (Windows, Macintosh, or whatever). Extract the contents of the downloaded file to a place on your computer's hard drive. The aforementioned contents is actually a directory full of stuff. The directory's name is flutter. Put your new flutter directory in a place that isn't protected with special privileges. For example, if you try extracting the flutter directory inside the c:\program files directory, Windows displays its User Account Control dialog box and asks for confirmation. Don't put the flutter directory inside a place like that. Many Flutter programmers like to put the flutter directory inside the home directory. This home directory usually contains a Documents directory, a Downloads directory, and lots of other stuff. After you extract the downloaded file's content, the home directory should have a brand-new flutter directory. You don't have to extract the flutter directory right inside your home directory, but it's the simplest, most reliable thing you can do. Make a note of the place on your hard drive where the new flutter directory lives. For example, if you copied the .zip file's contents to your /Users/janeqreader directory, make a note of the /Users/janeqreader/flutter directory. That's your Flutter SDK path. To make sure that you've extracted the downloaded file's contents correctly, look inside the flutter directory for a subdirectory named bin. Your mileage may vary, depending on when you download the Flutter SDK. Download the Android Studio IDE. The download is an .exe file, a .dmg file, or maybe something else. Install the software that you downloaded in Step 6. During the installation, a dialog box may offer the option of installing an Android virtual device (AVD). If so, accept the option. Android Studio isn't the only IDE that has features for creating Flutter apps. Some developers prefer Virtual Studio Code (known affectionately as VS Code) which is available for Windows, Macintosh, and Linux. And if you enjoy roughing it, you can do without an IDE and use the command line along with your favorite text editor — Emacs, vi, or Notepad. Learn more about Visual Studio Code. While you're visiting any software download site, check the requirements for downloading, installing, and running that software. Make sure you have enough memory and an operating system that's sufficiently up to date. Programming Flutter on your Mac If you have a Mac and you want to create iPhone apps, follow these steps: Select App Store from the Apple menu. In the store's search field, type Xcode and then press Enter. The App Store's search finds dozens of apps, but only one has the simple name Xcode. Click the Xcode app's Get button. As a result, the App Store installs Xcode on your computer. Launch the Xcode application. The first time you run Xcode, your Mac installs some additional components. If you want your apps to run on Apple devices, you need those additional components. Configuring Android Studio to program Flutter apps Android Studio doesn't come automatically with Flutter support, meaning you have to add Flutter support the first time you run the IDE. Here's what you do. Launch the Android Studio application. The first time you run a fresh, new copy of Android Studio, you see the Welcome screen. Select Configure→Plugins on the Welcome screen. You’ll find the Configure drop-down menu in the lower right corner of the Welcome screen. Search for a plugin named Flutter. Install that plugin. If Android Studio offers the option of installing Dart as well, accept the option. After installing the plugin, Android Studio may want to be restarted. Of course, you should restart it. When you do, you see the Welcome screen again. Now the Welcome screen includes the Start a New Flutter Project option. Ready to get started? Check out our Flutter Cheat Sheet.

View Article
Programming a Simple Switch in Your Flutter App

Article / Updated 07-16-2020

A Switch is a control in your Flutter app that's in one of two possible states: on or off, yes or no, true or false, happy or sad, over 18 or not. The following listing has the Flutter code for the practice Switch app. How Old Are You? import 'package:flutter/material.dart'; void main() => runApp(App0701()); class App0701 extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } const _youAre = 'You are'; const _compatible = 'compatible with\nDoris D. Developer.'; class _MyHomePageState extends State { bool _ageSwitchValue = false; String _messageToUser = "$_youAre NOT $_compatible"; /// State @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Are you compatible with Doris?"), ), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ _buildAgeSwitch(), _buildResultArea(), ], ), ), ); } /// Build Widget _buildAgeSwitch() { return Row( children: [ Text("Are you 18 or older?"), Switch( value: _ageSwitchValue, onChanged: _updateAgeSwitch, ), ], ); } Widget _buildResultArea() { return Text(_messageToUser, textAlign: TextAlign.center); } /// Actions void _updateAgeSwitch(bool newValue) { setState(() { _ageSwitchValue = newValue; _messageToUser = _youAre + (_ageSwitchValue ? " " : " NOT ") + _compatible; }); } } The images below show the Flutter app in its two possible states. Here’s one state. And here’s the other. What you find here are practice apps. They're bite-size samples of an example app called Doris's big, beautiful dating app. But even "bite-size" programs can be long and complicated. Sometimes, a few of the rules are bent and some good programming practices are ignored to make the listings compatible with one another. But, don't worry. Each listing works correctly, and each listing illustrates useful Flutter development concepts. You can find the entire dating app at this Flutter code resource. The Flutter code above has an onChanged parameter. The onChanged parameter's value is a function; namely, the _updateAgeSwitch function. When the user flips the switch, that flip triggers the switch's onChanged event, causing the Flutter framework to call the _updateAgeSwitch function. Note that the _updateAgeSwitch function in the code above isn't a VoidCallback. A VoidCallback function takes no parameters, but the _updateAgeSwitch function has a parameter. The parameter's name is newValue: void _updateAgeSwitch(bool newValue) When the Flutter framework calls _updateAgeSwitch, the framework passes the Switch widget's new position (off or on) to the newValue parameter. Because the type of newValue is bool, newValue is either false or true. It's false when the switch is off and true when the switch is on. If _updateAgeSwitch isn't a VoidCallback, what is it? (That was a rhetorical question, so let’s answer it for you. . . .) The _updateAgeSwitch function is of type ValueChanged. A ValueChanged function takes one parameter and returns void. The function's parameter can be of any type, but a ValueChanged function's parameter must be of type bool. In the same way, a ValueChanged function's parameter must be of type double. And so on. Make no mistake about it: Even though the term ValueChanged doesn't have the word Callback in it, the _updateAgeSwitch function is a callback. When the user flips the Switch widget, the Flutter framework calls your code back. Yes, the _updateAgeSwitch function is a callback. It's just not a VoidCallback. With many controls, nothing much happens if you don't change the control's value and call setState. For a few laughs, let’s try commenting out the setState call in the body of the _updateAgeSwitch function listed above: void _updateAgeSwitch(bool newValue) { // setState(() { _ageSwitchValue = newValue; _messageToUser = _youAre + (_ageSwitchValue ? " " : " NOT ") + _compatible; // }); } Next, let’s uncomment the setState call and comment out the assignment statements: void _updateAgeSwitch(bool newValue) { setState(() { // _ageSwitchValue = newValue; // _messageToUser = // _youAre + (_ageSwitchValue ? " " : " NOT ") + _compatible; }); } In both cases, the program was restarted and then the switch was tapped. Not only did the _messageToUser refuse to change, but the switch didn't even budge. That settles it! The look of the switch is completely dependent on the _ageSwitchValue variable and the call to setState. If you don't assign anything to _ageSwitchValue or you don't call setState, the switch is completely unresponsive. Want to learn more? Check out our Flutter Cheat Sheet.

View Article
What is Flutter?

Article / Updated 07-16-2020

At its core, Flutter is an API for creating apps. Most Flutter apps run on mobile devices, but Flutter apps can run on laptop and desktop computers, too. Flutter certainly wasn't the first API for mobile devices, so why should anyone consider using Flutter to create apps? Flutter allows for cross-platform development To get to the heart of Flutter, let’s consider a scenario that was retold by an app developer. My favorite burger joint advertised a new mobile ordering app. I needed the app so that I could quickly hop off a commuter train, grab a burger, and run to a nearby tech meeting. I did this several times each month. But I had a problem: The app ran only on iPhones, and I had an Android phone. Behind the scenes, the burger joint's app developers were hard at work converting their iPhone app to an Android app. This was no minor task, because Android's API doesn't recognize the same commands as iPhone's API. Going from one API to the other isn't straightforward. It's not a matter of making routine code changes. To convert from one kind of phone to another, developers rewrite thousands (and maybe even millions) of lines of code. The process is time-consuming and expensive. So I waited and waited for the restaurant to have an Android app. I was so desperate for a delicious cheeseburger that I finally broke down and bought a second phone. But that turned out to be a bad idea. As soon as my new iPhone arrived, the burger place released its shiny, new Android app. The moral of this story comes down to things called platforms. People throw around the word platform as if the word means everything and nothing. But in app development, a platform is a particular operating system along with the hardware the OS runs on. What makes the Android platform different from its iOS counterpart? To create radio buttons in Android's API, you write code of the following kind: RadioButton android:id="@+id/radioButton1" android:text="Red" android:onClick="onRadioButtonClicked" /> RadioButton android:id="@+id/radioButton2" android:text="Yellow" android:onClick="onRadioButtonClicked" /> RadioButton android:id="@+id/radioButton3" android:text="Green" android:onClick="onRadioButtonClicked" /> Try converting that code to work on an iPhone. The iOS API doesn't have radio buttons, so, to adapt an Android app with radio buttons for iOS, you write code to make things that look like radio buttons. You also code rules for the radio buttons to follow — rules like "only one button at a time can be selected." If you don't want to create radio buttons from scratch, you can replace Android's radio buttons with an iOS picker component, a thing that looks like an old automobile odometer. One way or another, replacing an app's components takes time and costs money. Some companies give up and create apps for only one platform — iPhone or Android. Other companies hire two teams of programmers — one for iPhone development and another for Android development. Still other companies have one team of programmers that work on both versions of the code. For the companies' managers, the problem is exasperating. Why spend nearly twice the money and create two apps that do almost the same things? The app developer community has names for this ugly situation: Software written for one platform isn't compatible with other platforms. The mobile phone arena suffers from fragmentation: The market is divided between two different operating systems, and the Android half is divided among many vendors' phones. A program that makes direct use of either the Android or iOS API is called native code, and native code written for Android can't run on an iOS device. In the same way, native code written for iOS is meaningless to an Android device. What's a developer to do? A framework is a second-level API. What the heck does that mean? A framework is an API that serves as an intermediary between the developer and some other API. If direct use of the Android or iOS API is problematic, you switch to a framework's API. The framework's API deals head-on with Android's and iOS's problems. Frameworks like Flutter offer an alternative to native app development. When you write a Flutter program, you don't write code specifically for Android or iOS. Instead, you write code that can be translated into either system's API calls. Here's how you create radio buttons in the Flutter framework: Radio( value: TrafficLight.Red, groupValue: _trafficLightValue, onChanged: _updateTrafficLight, ), Radio( value: TrafficLight.Yellow, groupValue: _trafficLightValue, onChanged: _updateTrafficLight, ), Radio( value: TrafficLight.Green, groupValue: _trafficLightValue, onChanged: _updateTrafficLight, ) Your computer translates code of this kind into either Android API calls or iOS API calls — or both. That's cool! Flutter offers a quick-and-easy development cycle There's no doubt about it — a long and arduous app development cycle hinders productivity. These days, shaving a few seconds off the turnaround time can make a huge difference. Here's what happens when you create an app for mobile devices: You write some code, or you modify some existing code. You don't write Android or iOS code on a phone of any kind. Phones aren't powerful enough for all the editing and other stuff you need to do. Instead, you create an app's code on a laptop or desktop computer. This laptop or desktop computer is called your development computer. You issue a command for your development computer to build the code. Building the code takes place in several stages, one of which is called compiling. Compiling means automatically translating your program from the source code you wrote to detailed object code instructions. Think of object code as a bunch of zeros and ones. It's very detailed and extremely unintuitive. Humans hardly ever read or write object code but, at the heart of things, processors respond only to object code instructions. In addition to the translation step, the build process connects the program you wrote with additional code that your program needs in order to run. For example, if your program accesses the Internet, the build process integrates your code with existing network code.What happens next? The development computer deploys your code to a target device. This so-called "device" may be a real phone connected to your computer or a picture of a phone on your computer's screen. One way or another, your program starts running. You press buttons, type text, and otherwise test your app to find out whether it's doing the things you want it to do. Of course, it's not doing all those things. So you return to Step 1 and keep trying. Steps 2 and 3 can be painfully slow. For some simple iPhone and Android apps, several minutes may go by as a computer prepares code for the program's next run. This sluggishness reduces productivity considerably. But along with Flutter comes some good news. Flutter uses the Dart programming language, and Dart comes with these two (count ’em — two) compilers: Ahead-of-time (AOT) compiler With an AOT compiler, your development computer translates an entire program and makes the translated code available for devices to run. No further translation takes place when the devices run your program. Each target device devotes its processing power to the efficient running of your code.An app running on AOT-compiled code runs smoothly and efficiently. Just-in-time (JIT) compiler With a JIT compiler, your development computer translates enough code to start the app running. It feeds this code to a test device and continues translating while the test device runs the app. If the developer presses a button on the test device's screen, the JIT compiler hurries to translate that button's code.An app running on a JIT compiler may appear to be sluggish because the compiler translates code while the app runs. But using a JIT compiler is a great way to test an app. Here's what happens when you develop a Flutter app: You write some code. You issue a command for your development computer to build the code. The first time around, building code can take some time. The development computer deploys your code to a target device.Again, you face a noticeable time lag. In testing your code, you find out that it's not doing all the things you want it to do. You modify your existing code, and then . . . You issue a command for your development computer to rebuild the code. Here's where Flutter's magic happens. Dart's JIT compiler recompiles only the part of the app that you've modified and sends the change straight to the target device. The modified code starts running in a fraction of a second. You save hours of time every day because you're not waiting for code changes to take effect. Flutter gives you two ways to apply changes to a running app: With hot restart, the app begins its run anew, removing any data that you've entered during the most recent test, displaying the app as if you're running it for the first time. With hot reload, the app takes up from where it left off, with the data you last entered intact, if possible. The only changes are the ones dictated by your modifications to the code. Flutter's hot restart and hot reload are both blazingly fast. They turn the app development cycle into a pleasure rather than a chore. Flutter provides a great way to think about app development The language you speak influences the way you think. If you don't believe this, look up the Sapir-Whorf hypothesis. You're bound to find it on your favorite linguistics website. Spoken languages are neither good nor bad, but programming languages can have good qualities and bad qualities. Most hybrid apps are written in the JavaScript programming language. Yes, JavaScript is one of the world's most widely used languages. But, no, JavaScript doesn't encourage good software design. It's easy to write confusing code in JavaScript because its rules are quite permissive. You can write sloppy JavaScript code, and the code runs just fine. That is, it runs fine until someone enters unexpected input. When that happens, you have trouble figuring out how your code was working in the first place. Even when you're not busy fixing errors, adding new features to JavaScript code can be difficult and frustrating. JavaScript aficionados will argue with every word in this paragraph but, one way or another, JavaScript has its downsides. Apple's iOS platform uses the Swift and Objective-C languages, whereas Android uses Kotlin and Java. Objective-C dates back to the early 1980s and it's showing its age. The other three languages fare pretty well on the scale of good language features, but none of them is as straightforward and intuitive as Dart. On top of that, both iOS and Android divide an app's code into two separate parts: Layout: How the app looks. Logic: The sequence of instructions that the app performs. The Android radio button example above is neither Kotlin nor Java code. It's XML code. It has a different format and lives in a different file from the code that responds to radio button choices. Separating layout from logic is a good thing. It puts distinct aspects of an app into different parts of the code. Developers can maintain each part independently. For an Android developer, that's a good thing. But this isn't an article about Android development. It's about Flutter. To that end, consider that separating layout from logic is not optimal. Here's why: You may have heard the all-encompassing mantra of Flutter app development: In Flutter, almost everything is a widget. And what is a widget? In a mobile app, every button is one of the app's widgets. Every text field is a widget. The app itself is a widget. The positioning of buttons and text fields is a widget. The animating of objects from one part of the screen to another is a widget. When you create a Flutter app, you put widgets inside of other widgets, which in turn are inside even more widgets. The code below has some fake code that illustrates the point: Like a Wheel Within a Wheel // Don't fall for the trickery. This isn't real Flutter code! Application( Background( CenterWhateverIsInsideThis( Button( onPressed: print("I’ve been clicked."), Padding( Text( "Click Me" ), ), ), ), ), ) This code has a Text widget inside of a Padding widget, which is inside of a Button widget inside a CenterWhateverIsInsideThis widget. That CenterWhateverIsInsideThis widget is inside a Background widget, which is inside an Application widget. The code is modeled after real Flutter code. The real Flutter code creates the app shown next. When the user presses the Button, the words I’ve been clicked appear. To see the real code that inspired the fake code you see here, check out this Flutter code and look for the big download link. The real code is in a file named app0101. Compare the image above and the one below. The to image shows the app as the user sees it. The following image shows the same app as the Flutter developer codes it. If you're not already a Flutter developer, the word widget might suggest a visible component, such as a button, a slider, an icon, or some other such thing. But in Flutter, things that aren't really visible are also widgets. For example, in the code listing above, CenterWhateverIsInsideThis is a widget. Having layout features like CenterWhateverIsInsideThis be widgets is a powerful idea. It means that Flutter developers can focus their attention on one overarching task — stuffing widgets inside other widgets. Flutter has a certain simplicity and elegance that other app development frameworks don't have. Flutter has no built-in widget named CenterWhateverIsInsideThis. But don't be disappointed. Flutter's Center widget does what the fictitious CenterWhateverIsInsideThis widget is supposed to do. Want to learn more about Flutter? Check out our Flutter Cheat Sheet.

View Article
10 Ways to Avoid Mistakes When Developing Flutter Apps

Article / Updated 07-10-2020

Flutter is a great resource for developing mobile apps. Similar to any programming project, one small mistake can cause big issues. Make sure to follow these ten guidelines to avoid mistakes in your Flutter app. Put capital letters where they belong The Dart language is case-sensitive. Don't type Class when you mean to type class. Don't type Runapp when you mean to type runApp. Use parentheses when (and only when) they're appropriate Remember the difference between _incrementCounter with parentheses: void _incrementCounter() { floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ) and _incrementCounter without parentheses: floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ) Limit access to Dart variables Wherever you can, avoid declaring top-level variables. To keep other files from changing your file's variables, start variable names with an underscore. Call setState If you press a widget and nothing happens, look for a method with a missing setState call. Make adjustments for indices starting at zero To make values start with 1, you have to add 1: return ListView.builder( itemCount: 25, itemBuilder: (context, index) => ListTile( title: Text('Rocky ${index + 1}'), onTap: () => goToDetailPage(index + 1), ), ); Use the Expanded widget When your test device displays black-and-yellow stripes or an empty screen, the layout you've coded is causing trouble. Consider wrapping one or more widgets inside Expanded widgets. Sometimes, it works wonders for your Flutter app. Add itemCount to your ListView.builder Without an itemCount parameter, the list of items never ends. Add imports when they're required For example, if you want to use Dart's math library, start your file with import 'dart:math'; If your Flutter app pulls data from the Internet, add this line to the top of your file: import 'package:http/http.dart'; Declare assets and dependencies in pubspec.yaml To display brokenheart.jpg and heart.jpg on the screen, add some lines to your Flutterproject's pubspec.yaml file: assets: - brokenheart.jpeg - heart.jpeg To get data from the Internet, add http to the file's list of dependencies: dependencies: flutter: sdk: flutter http: ^0.12.0+4 And remember, in a pubspec.yaml file, indentation matters. Indent your code according to Dart language guidelines Code that's not properly indented is difficult to read and difficult to maintain. Format your code by selecting Code→Reformat Code from Android Studio's main menu. Want to learn more? Check out our Flutter Cheat Sheet.

View Article
page 1
page 2