Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

awesome flutter tips and tricks

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 {}

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.