Flutter Gists

Flutter RaisedButton: callback function

See below example:


int  result = 0;
void calculate(num1, num2) {
 setState(() {
     result = num1 + num2;
 });
}
new RaisedButton(
      onPressed: () => calculate(1, 100),
      ...
),
new Text("$result")

  1. onPressed: calculate(1, 100),

calculate(1, 100) will be called every time Flutter runs build()

  1. onPressed: () => calculate(1, 100),

The same as onPressed: () {calculate(1,100);}

When the button pressed, then call back the function

  1. onPressed: calculate,

if the function has no parameters, When the button pressed, then call back the function.

================================================================================

Flutter builder: builder example

See below example:

showDialog(
    context: context,
    builder: new Builder(builder: (_) => myWidget),
);

equal to:

showDialog(
    context: context,
    builder: (_) => myWidget,
);

================================================================================

Flutter create a StatefulWidget example

class MyApp extends StatefulWidget
{
@override
// _myState here is actually a type, not a variable name.
_myState createState() => _myState();
}  

equal to:

@override
_myState createState() {
    return new _myState();
}

================================================================================

Flutter Redirecting constructors example

class Automobile {
    String make;
    String model;
    int mpg;

    // The main constructor for this class.
    Automobile(this.make, this.model, this.mpg);

    // Delegates to the main constructor.
    Automobile.hybrid(String make, String model) : this(make, model, 60);

    // Delegates to a named constructor
    Automobile.fancyHybrid() : this.hybrid('Futurecar', 'Mark 2');
}

class Color {
    int red;
    int green;
    int blue;

    Color(this.red, this.green, this.blue);

    Color.black() : this(0, 0, 0);
}

================================================================================

Colon in Dart Constructor Syntax

The code below assigns the parameter named number to the final field this.number if it is non-null and otherwise it assigns 0. This means that the left-hand number of the assignment actually refers to this.number. Now, you can even make an assertion that will never fail (and is redundant because of that):


class X {
  final int number;
  X(number): number = number ?? 0, assert(number != null);
}

This “:” feature in Dart is called “initializer list”. It allows you to initialize fields of your class, make assertions and call the super constructor.


class Point {
  num x, y;
  Point(this.x, this.y);
  Point.origin(): this.x = 10, this.y = 10;
}

main() {
  Point p = Point.origin();
  print(p.x); // 10
  print(p.y); // 10
}

================================================================================

End