• Stars
    star
    331
  • Rank 127,323 (Top 3 %)
  • Language
    Dart
  • License
    Apache License 2.0
  • Created almost 6 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Useful Flutter and Dart Tips.
Table of Contents

Articles

Tips

16. Apply HitTestBehavior.opaque on GestureDetector to make the entire size of the gesture detector a hit region

If your GestureDetector isn't picking up gestures in a transparent/translucent widget, make sure to set its behavior to HitTestBehavior.opaque so it'll capture those events.

GestureDetector(
  behavior: HitTestBehavior.opaque,
  onTap: ()=>print('Tap!'),
  child: Container(
  height: 250,
  width: 250,
  child: Center(child: Text('Gesture Test')),
 ),
),

Opaque targets can be hit by hit tests, causing them to both receive events within their bounds and prevent targets visually behind them from also receiving events.

Original source: Twitter

15. Check if release mode or not

You can use kReleaseMode constant to check if the code is running in release mode or not. kReleaseMode is a top-level constant from foundation.dart.

More specifically, this is a constant that is true if the application was compiled in Dart with the '-Ddart.vm.product=true' flag. (from https://api.flutter.dev/flutter/foundation/kReleaseMode-constant.html)

import 'package:flutter/foundation.dart';

print('Is Release Mode: $kReleaseMode');

14. Set background image to your Container.

Want to set the background image to your Container? And you are using a Stack to do so? There is a better way to achieve this result. You can use decoration to set the image in the container.

Container(
  width: double.maxFinite,
  height: double.maxFinite,
  decoration: BoxDecoration(
    image: DecorationImage(
      image: NetworkImage('https://bit.ly/2oqNqj9'),
    ),
  ),
  child: Center(
    child: Text(
      'Flutter.dev',
      style: TextStyle(color: Colors.red),
    ),
  ),
),

You can provide Image according to your need, also you can use the box decoration properties to provide shape and border.

13. Prefer single quotes for strings

Use double quotes for nested strings or (optionally) for strings that contain single quotes. For all other strings, use single quotes.

final String name = 'Flutter And Dart Tips';

print('Hello ${name.split(" ")[0]}');
print('Hello ${name.split(" ")[2]}');

12. Implement assert() messages in Dart.

Do you know that you can throw your message when your assert fails? assert() takes an optional message in which you can pass your message.

assert(title != null, "Title string cannot be null.");

11. Using Plurals in your Dart String.

Plurals: Different languages have different rules for grammatical agreement with quantity. In English, for example, the quantity 1 is a special case. We write "1 book", but for any other quantity we'd write "n books". This distinction between singular and plural is very common, but other languages make finer distinctions.

You can use Plurals in your Dart string by using Intl package. The full set supported by Intl package is zero, one, two, few, many, and other.

  • Add dependency:
dependencies:
  intl: version
  • How to use:
import 'package:intl/intl.dart';
...
notificationCount(int howMany) => Intl.plural(
      howMany,
      zero: 'You don\'t have any notification.',
      one: 'You have $howMany notification.',
      other: 'You have $howMany notifications.',
      name: "notification",
      args: [howMany],
      examples: const {'howMany': 42},
      desc: "How many notifications are there.",
    );

    print(notificationCount(0));
    print(notificationCount(1));
    print(notificationCount(2));
    
  • Output:
You don't have any notification.
You have 1 notification.
There are 2 notifications.

10. Having trouble displaying splashes using an InkWell?

Use an Ink widget! The Ink widget draws on the same widget that InkWell does, so the splash appears. #FlutterFriday tweet by Flutter.dev.

Learn more here.

class InkWellCard extends StatelessWidget {
  Widget build(BuildContext context) {
    return Card(
      elevation: 3.0,
      child: Ink(
        child: InkWell(
          child: Center(
            child: Text("Order Bagels"),
          ),
          onTap: () => print("Ordering.."),
        ),
      ),
    );
  }
}

9. Want to log data on the system console in Flutter?

You can use the print() function to view it in the system console. If your output is too much, then Android sometimes discards some log lines. To avoid this, you can use debugPrint().

You can also log your print calls to disk if you're doing long-term or background work.

Check out this Gist by Simon Lightfoot

8. Cascade Notation - Method Chaining on Steroids 💊💉

Cascades Notation (..) allows chaining a sequence of operations on the same object. Besides, fields (data-members) can be accessed using the same.

Open in DartPad 🎯

class Person {
  String name;
  int age;
  Person(this.name, this.age);
  void data() => print("$name is $age years old.");
}

void main() {
   // Without Cascade Notation
   Person person = Person("Richard", 50);
   person.data();
   person.age = 22;
   person.data();
   person.name += " Parker";
   person.data();
   
   // Cascade Notation with Object of Person
   Person("Jian", 21)
    ..data()
    ..age = 22
    ..data()
    ..name += " Yang"
    ..data();
    
   // Cascade Notation with List
   List<String>()
    ..addAll(["Natasha", "Steve", "Peter", "Tony"])
    ..sort()
    ..forEach((name) => print("\n$name"));
}

7. Want to set different Theme for a particular widget?

Just wrap the widget with the Theme Widget and pass the ThemeData().

Theme(
  data: ThemeData(...),
  child: TextFormField(
    decoration: const InputDecoration(
      icon: Icon(Icons.person),
      hintText: 'What do people call you?',
      labelText: 'Name *',
    ),
    onSaved: (String value) {
      // This optional block of code can be used to run
      // code when the user saves the form.
    },
    validator: (String value) {
      return value.contains('@')
        ? 'Do not use the @ char'
        : null;
    }
  ),
)

6. Use a Ternary operator instead of the if-else to shorter your Dart code.

Use below.

void main() {
  bool isAndroid = true;
  getDeviceType() => isAndroid ? "Android" : "Other";
  print("Device Type: " + getDeviceType());
}

Instead of this.

void main() {
  bool isAndroid;
  getDeviceType() {
    if (isAndroid) {
      return "Android";
    } else {
      return "Other";
    }
  }
  print("Device Type: " + getDeviceType());
}

5. Want to run a task periodically in Dart?

What about using Timer.periodic It will create a repeating timer, It will take a two-argument one is duration and the second is callback that must take a one Timer parameter.

Timer.periodic(const Duration(seconds: 2), (Timer time) {
  print("Flutter");
});

You can cancel the timer using the timer.cancel().

4. Apply style as a Theme in a Text widget.

Check out the below article for detail information about this tip. Apply style as a Theme in a Text widget

Text(
  "Your Text",
  style: Theme.of(context).textTheme.title,
),

3. Do not explicitly initialize variables to null.

Adding = null is redundant and unneeded.

// Good
var title;

// Bad
var title = null;

2. Using ListView.separated()

Want to add the separator in your Flutter ListView?

Go for the ListView.separated();

The best part about separated is it can be any widget.😃

Check out the below image for the sample code.

ListView.seperated(
  seperatorBuilder: (context, index) => Divider(),
  itemBuilder: (BuildContext context, int index) => new ExampleNameItem(
    exampleNames: names[index],
  ),
  itemCount: names.length,
  padding: new EdgeInsets.symetric(
    vertical: 8.0,
    horizontal: 8.0,
  ),
);

1. Using null-aware operators

While checking the null in the Dart, Use null-aware operators help you reduce the amount of code required to work with references that are potentially null.

// User below

title ??= "Title";

// instead of

if (title == null) {
  title = "Title";
}

More Repositories

1

FlutterPlayground

Playground app for Flutter
Dart
1,071
star
2

Fluttery-Filmy

🎥 Movie app which is developed using flutter and powered by tmdb.
Dart
196
star
3

Constraint-Layout-Animations

Kotlin
186
star
4

flutter-best-practices

Do's and Don'ts for Flutter development
Dart
97
star
5

youtube_flutter_app

Dart
84
star
6

flutter_google_map

Dart
67
star
7

cricket_team

Dart
45
star
8

flutter_finger_scan_animation

Fingerprint scan animation
Dart
42
star
9

ExpandingCardAnimation

Dart
41
star
10

flutter_movie_app

Dart
37
star
11

supabase_playground

Trying to develop an open source social media app
Dart
37
star
12

flutter_mobx_boilerplate

A Flutter Project contains a Boilerplate code with MobX and Provider as a State Management.
Dart
31
star
13

rounded_floating_app_bar

An easy way to add rounded corner floating app bar in Flutter project.
Dart
30
star
14

itsallwidgets_podcast

it's all widget podcast
Dart
29
star
15

AnimatedIcons

Dart
27
star
16

flutter_ios_playground

Dart
26
star
17

SplashAnimations

Dart
24
star
18

sample_data

generate random sample data to test your application.
Dart
19
star
19

flutter_extension

Dart
16
star
20

ProgressButton

Dart
16
star
21

nectar

A Flutter application UI for Online Grocery store.
Dart
13
star
22

UdacityAppClone

Kotlin
9
star
23

FlutterAnimatedSize

Dart
8
star
24

WidgetVisibilty

Sample on how to manage the Visiblity of the widget in flutter.
Dart
8
star
25

MarvelousPortal

Kotlin
5
star
26

gdg_ahmedabad_codelab

Dart
5
star
27

PopularMovies

🎥 Popular Movies App is the second project in Udacity's Android Developer Nanodegree.
Java
5
star
28

ibhavikmakwana.me

A Flutter Website Portfolio
Dart
4
star
29

reply

Dart
4
star
30

flutter_meditation_app

Dart
3
star
31

UdacityPraticalQuiz

Kotlin
3
star
32

flutter_contra_wireframe_app

Dart
3
star
33

mobx_theme_switcher

Dart
3
star
34

ExpandableCardView

Expandable Card View in Kotlin
Kotlin
3
star
35

TicTacToe

Challenge of the Google India Devloper Scholarship
Kotlin
3
star
36

flutter_states_rebuilder_app

Dart
3
star
37

flutter_blocks

Dart
3
star
38

fire_auth

Dart
3
star
39

flutter_play_search

Dart
2
star
40

ErrorPage

Kotlin
2
star
41

leaf_lens

Dart
2
star
42

flutter_sample_app

Dart
2
star
43

files_clone

Dart
2
star
44

flutter_first_flight

Dart
2
star
45

devo

Dart
2
star
46

FlutterModuleDemo

Dart
2
star
47

devfest

Dart
1
star
48

magic_link_example

Dart
1
star
49

flutter_fire_odm

C++
1
star
50

ibhavikmakwana

1
star
51

flutter_forward_ranchi

C++
1
star