Chapter 10
Ten Ways to Avoid Mistakes
IN THIS CHAPTER
Spotting common errors
Using proper code style
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() {
setState(() {
_counter++;
});
}
and _incrementCounter
without parentheses:
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
)
For details, refer to Chapter 5.
Limit Access to 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. (Refer to Chapter 5.)
Call setState
If you press a widget and nothing happens, look for a method with a missing setState
call. (Refer to Chapter 5.)
Make Adjustments for Indices Starting at Zero
To make values start with 1, you have to add 1 (Refer to Chapter 8.):
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. (Refer to Chapters 6 and 8.)
Add itemCount to Your ListView.builder
Without an itemCount
parameter, the list of items never ends. (Refer to Chapter 8.)
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 app pulls data from the Internet, add this line to the top of your file:
import 'package:http/http.dart';
For details, refer to Chapters 8 and 9.
Declare Assets and Dependencies in pubspec.yaml
To display brokenheart.jpg
and heart.jpg
on the screen, add some lines to your project’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
For details, refer to Chapters 3 and 8. 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.