❤️Flutter ❤️ tips and tricks ❤️ Awesome Flutter ❤️ tips and tricks ❤️

Overview

❤️ Awesome Flutter ❤️ tips and tricks ❤️

Hits Awesome Flutter

Tip 1 : stless & stful

We can type stless and stful and we get Autocomplete Suggestion to generate Stateless Flutter Widget or Stateful Flutter Widget Respectively.

statful

Tip 2 : If Null Operator (??)

?? checks If something is null. If it's not null it returns its own value but if it's null it returns the value after ??

return abc??10; //returns 10 if abc is null else returns its own value,

It also has shorthand assignment when it's null.

abc??=5 //assigns 5 to abc if it's null

testOldMethod() {
  print("NullChecking in old way");
  var abc;
  
  if (abc == null) {
    print("It's null");
  } else {
    print(abc);
  }

  if (abc == null) {
    abc = 5;
  }
}

testIfNullOperator() {
  print("NullChecking with if Null Operator");
  var abc;

  print(abc ?? "It's null");
  abc ??= 5;
  print(abc ?? "It's null");
}

Output:

NullChecking in old way
It's null
5
--------------------
NullChecking with if Null Operator
It's null
5

Tip 3 : Inner Function

We can define a function inside another function.

This is to encapsulate the inner function from everything else outside the outer function.

main() {
  String getName() {

    String getFirstName() { return "Laxman"; }

    String getLastName() { return "Bhattarai"; }

    return getFirstName() + " " + getLastName();
  }

  print(getName());
}

Output

Laxman Bhattarai

Tip 4 : ..Cascade..Chaining..Fluent API

We can chain method/member calls without returning this from method(), getter() and setter() using cascade operator (..)

try in Dartpad

Before:

class User {
  String name;
  int age;

  User({this.name = "Foo", this.age = 0});

  User withName(String name) {
    this.name = name;
    return this;
  }

  User withAge(int age) {
    this.age = age;
    return this;
  }

  void printId() => print("$name is $age years old.");
}

main() {
  User()
  .withAge(27)
  .withName("Laxman")
  .printId();
}

Can be replaced with

class User {
  String name;
  int age;

  void printId() => print("$name is $age years old.");
}

main() {
  User()
  ..age = 27
  ..name = "Laxman"
  ..printId();
}

Tip 5 : Dart data class

Dart does not support data class by default, but with plugins, we can simply generate data class (copyWith(),fromMap(), toMap(), Named Constructor, toString(),hashCode() & equals() methods implemented by the tool).

🚨❗️Caution❗️🚨 : Your cursor should be inside the class that you want to generate data class.

dataclass

Download Plugins :

For Android Studio

For VsCode

Tip 6 : RichText Widget

If you want to have a single text with different style within it? Do not bother or try to hack with with Text() and use RichText() with TextSpan()

Try on dartpad

See Youtube Demo

richtext

Tip 7 : Spacer Widget

Using Container with certain height/width to create responsive space between Widgets? That may look good on one screen but will not look the same in different screen size.

Spacer Widget comes for the rescue. Instead of Container(width: / height: ), use Spacer(flex: ).

How on this earth did I not know about this widget earlier? This is going to save many lives 😂

Try on dartpad

See Youtube Demo

spacer

Tip 8 : ListView.separated()

If you have you been adding Container() with maxwidth at the bottom of ListItem to put divider line like me, you have been doing it wrong all the time.

Flutter has ListView.separated just for that purpose. We have to also provide separatorBuilder in addition to what we already passed while using ListView.builder

Bonus 🍾 🎁 🎊 🎉 : You do not have to check if the item is last in order not to draw divider after the last item.

try in dartpad

ListView.separated(
  itemCount: 25,
  separatorBuilder: (BuildContext context, int index) => Divider(
    thickness: 1,
  ),
  itemBuilder: (BuildContext context, int index) {
    return ListTile(
      title: Text(
        'Index Number $index',
      ),
    );
  },
);

Tip 9 : Passing Function as parameter

We can simply pass a function as parameter like we pass a variable. When we want to call the passed function from calling function, we just call it with () at the end along with parameters if it accepts any.

try in dartpad

void main() {
  f2(f1, 3);
  f2(f1, 4);
  f2(f1, 7);
}

f1(int venOrOdd) {
  print("$evenOrOdd is ${evenOrOdd % 2 == 0 ? "Even" : "Odd"}");
}

f2(Function(int) evenOrOddFunction, int argumentToPass) {
  evenOrOddFunction(argumentToPass);
}

OutPut

3 is Odd
4 is Even
7 is Odd

Tip 10 : Relative Import : the right way to import .dart files we have in our lib package

Ever wondered what is the right way to import a file in your own package?

Prefer relative imports to absolute imports.

Why?

  • It's shorter and cleaner.
  • We can easily differentiate our files and third-party ones.
  • It makes sense, doesn't it?
my_package
└─ lib
   ├─ src
   │  └─ utils.dart
   └─ api.dart

If api.dart wants to import utils.dart, it should do so using:

import 'src/utils.dart';

And not:

import 'package:my_package/src/utils.dart';

Tip 11 : Reusing Text Style

Tired of defining textStyle everytime you want to customize Text? Even worse if you have multiple theme (dark, light, full black theme etc).

just use

Theme.of(context).textTheme.title

where there are other styles like title inside textTheme.

try in dartpad with theme example

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

Tip 12 : Use Literal to initialize growable collections

If we are to initialize growable collection, use literal initialization rather than with constructors.

// Good
var points = [];
var addresses = {};

// Bad
var points = List();
var addresses = Map();

// With type argument

// Good
var points = <Point>[];
var addresses = <String, Address>{};

// Bad
var points = List<Point>();
var addresses = Map<String, Address>();

Tip 13 : Fat arrow functions

We can use fat arrow => members (function, getter,setter) in dart.

I would not use => if the declaration is not ONE LINER. But few lines are OK.

try on dartpad

void main() {
  User()
    ..firstName = "Laxman"
    ..lastName = " Bhattarai"
    ..age = 18
    ..printUser();
}

class User {
  String firstName;
  String lastName;
  DateTime birthday;

  String get fullName => firstName + lastName;

  set age(int age) =>  birthday = DateTime.now().subtract(Duration(days: age * 365));

  int get age => DateTime.now().year - birthday.year;

  bool get isAdult => age >= 18;

  printUser() => print(fullName + " is a ${isAdult ? "Adult" : "Child"}");
}

Tip 14 : FractionallySizedBox

Ever wanted the widget to have height and width exactly in the same proportion to it's screen's height and width?

FractionallySizedBox is build exactly for that use case. Just give it the fraction you need for your height and width and it will handle everything else. The fraction value will range between 0.0 to 1.0

FractionallySizedBox(
  widthFactor: 0.5,
  heightFactor: 0.5,
  child: Container(color: Colors.green),
)

try on codepen

fractionally

Tip 15 : Flexible vs Expanded

Expanded() is nothing more than Flexible() with

Flexible (fit: FlexFit.tight) = Expanded()

but, Flexible uses fit :FlexFit.loose by default.

FlexFit.tight = Wants to fit tight into parent taking as much space as possible.

FlexFit.loose = Wants to fit loose into parent taking as little space as possible for itself.

flex = The factor of space taken from parent. Mostly not fully used if flex: FlexFit.loose used i.e. Flexible.

flex

If you fully read the following image, you will fully understand the difference between Flexible and Expanded

class Flexible extends... {
  /// The flex factor to use for this child
  ///
  /// If null or zero, the child is inflexible and determines its own size. If
  /// non-zero, the amount of space the child's can occupy in the main axis is
  /// determined by dividing the free space (after placing the inflexible
  /// children) according to the flex factors of the flexible children.
  final int flex;

  /// How a flexible child is inscribed into the available space.
  ///
  /// If [flex] is non-zero, the [fit] determines whether the child fills the
  /// space the parent makes available during layout. If the fit is
  /// [FlexFit.tight], the child is required to fill the available space. If the
  /// fit is [FlexFit.loose], the child can be at most as large as the available
  /// space (but is allowed to be smaller).
  final FlexFit fit;

  ........
}

class Expanded extends Flexible {
  /// Creates a widget that expands a child of a [Row], [Column], or [Flex]
  /// so that the child fills the available space along the flex widget's
  /// main axis.
  const Expanded({
    Key key,
    int flex = 1,
    @required Widget child,
  }) : super(key: key, flex: flex, fit: FlexFit.tight, child: child);
}

try in codepen

Tip 16 : Bulk declaration

If you have been declaring each member separately all the time, you can declare members of same types at once.

I wouldn't declare age and shoeSize at once because they are not related.

With great power comes great responsibility, Use this wisely.

class Footballer {

  String firstName = "Lionel";
  String middleName = "Andrés";
  String lastName = "Messi";

  double weightKG;
  double heightCM;

  int goals;
  int assists;
  int tackles;
  int takeons;
  int saves;
  int shots;
}

// The class above can be replaced with:
class Footballer {

  String firstName = "Lionel", middleName = "Andrés", lastName = "Messi";

  double weightKG, heightCM;

  int goals, assists, tackles, takeons, saves, shots;
}

Tip 17 : SliverAppBar / Collapsable AppBar / ParallaxHeader

Remember CollapsableAppBar (android) / ParallaxHeader (ios)? We have SliverAppBar in Flutter to do exactly that.

To use it, you will have to have a CustomScrollView as parent.

then you add two slivers of it.

  1. SliverAppBar
  2. SliverFillRemaining

You can play with values of snap, floating, pinned etc to get desired effect

try on dartpad

see various types of SliverAppBars here

sliverappbar

Tip 18 : What the Key

keys

Ever wondered why we need GlobalKey(children : GlobalObjectKey, LabeledGlobalKey), LocalKey(children: ObjectKey, ValueKey & UniqueKey) right?

They are used to access or restore state In a statefulWidget (Mostly we don't need them at all if our widget tree is all Stateless Widgets).

Purpose (Key to use inside bracket)

  • Mutate the collection i.e. remove / add / reorder item to list in stateful widget like draggable todo list where checked items get removed (ObjectKey, ValueKey & UniqueKey)
  • Move widget from one Parent to another preserving it's state. (GlobalKey)
  • Display same Widget in multiple screens and holding its state.(GlobalKey)
  • Validate Form.(GlobalKey)
  • You can to give a key without using any data. (UniqueKey)
  • If you can use certain field of data like UUID of users as unique Key. (ValueKey)
  • If you do not have any unique field to use as key but object itself is unique. (ObjectKey)
  • If you have multiple Forms or Multiple Widgets of same type that need GlobalKey. (GlobalObjectKey, LabeledGlobalKey whichever is appropriate , similar logic to ValueKey and ObjectKey)

Learn more on this video

Tip 19 : Amazing Library time.dart

If you are tired to long and verbose DateTime and Duration calculation time.dart comes to your rescue.

//Before
var 3dayLater = DateTime.now().add(Duration(days: 3)).day;

//After
var 3dayLater = 3.days.fromNow.day;

//Before
var duration = Duration(minutes: 10) +Duration(seconds: 15) 
  - Duration(minutes: 3) + Duration(hours: 2;

//After
var duration = 10.minutes + 15.seconds - 3.minutes + 2.hours;

//Before
await  Future.delayed(Duration(seconds: 2))

//After
await 2.seconds.delay

visit time.dart

Tip 20 : Testing errors

You can simply test if two values are equal in dart with expect(actual, expected)

But if you want to test errors use the function closure that throws error as actual and check with throwsA<ErrorType> as expected.

void main() {
  group("Exception/Error testing", () {
    test("test method that throws errors", () {
      expect(_testError(fails: false), false);
      expect(() => _testError(fails: true), throwsA(isA<FooError>()));
    });
  });
}

bool _testError({bool fails}) {
  if(fails)throw FooError();
    return fails;
}

class FooError extends Error {}

Tips 1-20 Next >>

Tips 41-60 Tips 61-80 Tips 81-100

Comments
  • Making pages of 20 items instead of just 7.

    Making pages of 20 items instead of just 7.

    One of the aspects I liked about putting all tips in a single page was that I could just keep scroll without navigation.

    Now it needs action from the reader which is an additional burden that will reduce the average consumption amount.

    I am not sure if anybody is seeing issues in this repo (please put some reaction if you do, just to let me know that you see them), but I would want to discuss this before making change.

    20 tips a page is the sweet spot I think will have a good enough loading time and the continuous supply of tips in a single Page.

    help wanted 
    opened by erluxman 12
  • Images inside examples are too big

    Images inside examples are too big

    Generally - when you are using an image (or GIF) you can control the size of the image so it won't be too big (as for the moment its kind of too big).

    Example:

    • <img src="your image link" height="450">
      
    • <img src="your image link" width="450">
      

    You can also use both height and width together

    • <img src="your image link" height="450" width="450">
      
    opened by Tamir198 3
  • Addition of Enum extensions

    Addition of Enum extensions

    A powerful but not very well known feature. Allows for custom function prototypes to be defined for Enumeration types. Can be very useful in situations such as getting the value of an enumeration type in string. Check out this link for an example.

    opened by rootsec1 3
  • Example image for tip #24 is too big

    Example image for tip #24 is too big

    It would be better to make it smaller: https://github.com/erluxman/awesomefluttertips/blob/master/page2.md#tip-24--rectangular-fab-with-notched-bottom-appbar

    opened by sebastiandenis 2
  • Replace code images with code blocks

    Replace code images with code blocks

    As commented on issue #42 , this PR replaces code images with code blocks. It also specifies the code language on some code blocks to improve the highlight.

    I've not been able to replace all code images, don't have much time now, sorry...

    opened by EsteveAguilera 1
  • Change Code block to dart code

    Change Code block to dart code

    Make use syntax highlighting using a specific language.

    How to use:

    ```dart
    code block
    ` ``
    

    Before

    // Without the ```code_language
    final name = 'Haris';
    

    After

    // With the ```code_language
    final name = 'Haris';
    
    enhancement 
    opened by happyharis 1
  • Use syntax highlighting for code blocks

    Use syntax highlighting for code blocks

    I've added syntax highlighting for the code blocks on the first page to add some colour and make them easy to read.

    BTW, while code images can be nice looking, will you consider a PR that replaces all (static) code images with code blocks?

    The code images are not consistent, they've different sizes, colours, and they're generally really big.

    Code blocks will still be syntax highlighted and will add homogeneity and enable visitors to copy the code.

    opened by EsteveAguilera 0
  • Replace code images with code blocks

    Replace code images with code blocks

    While code images can be nice looking, will you consider a PR that replaces all (static) code images with code blocks?

    The code images are not consistent, they've different sizes, colours, and they're generally really big.

    Code blocks will still be syntax highlighted and will add homogeneity and enable visitors to copy the code.

    I already mentioned that on PR #41 where I added syntax highlighting on some code blocks.

    opened by EsteveAguilera 4
  • Stateful / Stateless Widget Shortcut

    Stateful / Stateless Widget Shortcut

    Shortcut for generating stateful/stateless widgets is either:

    "st" + enter = Stateful Widget "st" + downarrow + enter = Stateless Widget

    or

    "stf" + enter = Stateful Widget "stl" + enter = Stateless Widget

    opened by pradt 2
Owner
Laxman Bhattarai
Android & Flutter Developer. 🔝Top rated developer in Upwork.
Laxman Bhattarai
A Collection of Flutter and Dart Tips and Tricks

A Collection of Flutter and Dart Tips and Tricks

Vandad Nahavandipoor 5.7k Dec 27, 2022
An awesome Flutter 3d project by Flutter_Cube package

flutter3d A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

Azamatjan 1 Oct 26, 2021
A curated list of awesome cheats needed to quickly get started with flutter development.

dart-cheat-sheet A curated list of awesome stuff needed to get started with your flutter development journey Table of Contents String interpolation Fu

Temidayo Adefioye 137 Jan 2, 2023
It says it all. Not In Flutter Docs, a sort of underground guide to flutter app development and design.

Not In Flutter Docs It says it all. Not In Flutter Docs, a sort of underground guide to flutter app development and design. Licenses Code is under BSD

Fred Grott 56 Dec 27, 2022
Based on Microsoft Fluent Design System and made using the help of Flutter VelocityX.

Vx Fluent UI for Flutter Based on Microsoft Fluent Design System and made using the help of Flutter VelocityX. VxFluentUI is a Flutter component libra

Pawan Kumar 14 Jan 28, 2022
A Flutter implementation of an expandable and animated floating search bar, also known as persistent search.

Material Floating Search Bar A Flutter implementation of an expandable floating search bar, also known as persistent search, similar to the ones used

null 390 Mar 3, 2022
A Flutter widget that scrolls text widget and other widget

marquee_widget A Flutter widget that scrolls Widget Text and other Widget with supported RTL. Provides many customizationsincluding custom scroll dire

Yousif Khalid 23 Nov 21, 2022
🎓Flutter TodoList tutorial

Todo List built with Flutter Built with Git Tutor This tutorial will walk you through the process of building of a simple todo-list with Flutter Getti

Andrei Lesnitsky 294 Dec 29, 2022
Highly Subjective Roadmap to Flutter Development

Flutter Roadmap Dev Environment https://learngitbranching.js.org Language https://dart.dev/guides/language/language-tour https://dart.dev/guides/langu

Oleksandr Leuschenko 4.3k Jan 2, 2023
Learn to Code While Building Apps - The Complete Flutter Development Bootcamp

Learn to Code While Building Apps - The Complete Flutter Development Bootcamp

London App Brewery 9.3k Dec 31, 2022
Learn Flutter in 30 Days

flutter_catalog A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Pawan Kumar 329 Dec 29, 2022
Personal Knowledge Base (PKB). Flutter Responsive Web, Desktop, Android, iOS app. MobX as state management.

PKB - Responsive Flutter Web / Desktop / Android / iOS "Personal Knowledge Base" app written on Flutter. >> View DEMO Video About project This project

Vladimir 21 Oct 10, 2022
Flutter Portfolio App Concept - Day 33

Flutter Portfolio App Concept - Day 33

Mohammad Rahmani 29 Nov 10, 2022
Flutter Tutorial - Speech To Text & Voice Recognition

Flutter Tutorial - Speech To Text & Voice Recognition Let's build a Speech To Text Flutter app which recognizes & analyzes your words to execute comma

null 0 Nov 3, 2021
A flexible multi select package for Flutter. Make multi select widgets the way you want.

Multi Select Flutter Multi Select Flutter is a package for creating multi-select widgets in a variety of ways. Dialog BottomSheet ChoiceChip Features

null 177 Dec 20, 2022
Animal Sounds App written in flutter for the #100daysOfCode

animalsounds A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Antonio Giordano 0 Jan 9, 2022
Amazon Bookshelf Interface Design made in Flutter

amazon_ui_clone A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Emanoel Santana 0 Nov 25, 2021
Flutter.io - How Many People Are In Space Right Now?

hmpaisrn A new Flutter application. How Many People Are In Space Right Now? Google Play Store https://play.google.com/store/apps/details?id=de.bergera

berger 13 Mar 16, 2021
App concept created with Flutter using Dart programming language, inspired by Multi Search By Categories.

Photography Explorer Flutter App App concept created with Flutter using Dart programming language, inspired by Multi Search By Categories. About This

Wilton Neto 103 Sep 28, 2022