Flutter Misc - splimter/Flutter GitHub Wiki

Flutter Animation

theme Default visual properties, like colors fonts and shapes, for this app's material widgets.

  • ThemeData Holds the color and typography values for a material design theme.
  • primarySwatch Defines a single color as well a color swatch with ten shades of the color.

Animation<T> An animation consists of a value (of type T) together with a status. The status indicates whether the animation is conceptually running from beginning to end or from the end back to the beginning.

AnimationController A controller for an animation.

Tween(begin: <val>, end: <val>A linear interpolation between a beginning and ending value.

CurvedAnimation(parent: AnimationController, curve: Curve is useful when you want to apply a non-linear Curve to an animation object,

  • Curves.easeIn A cubic animation curve that starts slowly and ends quickly.

AnimationStatus The status of an animation

AnimatedBuilder is useful for more complex widgets that wish to include an animation as part of a larger build function.

GestureDetector A widget that detects gestures.

Transform A widget that applies a transformation before painting its child.

for veiw helper use the flag debugPaintSizeEnabled = true; in main, need to be imported import 'package:flutter/rendering.dart';.

Setting up animation

First we need to declare the animation:

  Animation<double> <varAnim>;
  AnimationController <varCont>;

After that we set the initial state:

initState() {
	super.initState();
	<varCont> = AnimationController(
		duration: Duration(<TIME>: <val>),
		vsync: this,
	);
    <varAnim> = Tween(begin: <iniVal>, end: endVal)
        .animate(CurvedAnimation(parent: <varCont>, curve: Curves.<eum>));

you can add a listener:

<varAnim>.addStatusListener((status) {
	if (status == AnimationStatus.<STATUS>)
	<varCont>.<Action>;
});

you can use the AnimationController object to invok some action like:

<varCont>.forward();	// start the animation from 0 to 1.
<varCont>.reverse();	// replay the animation from 1 to 0.
<varCont>.reset();		// reset the animation to 0.

Checkout this exemple.

Audio

Dependencies:

dependencies:
  audioplayers: ^0.10.1

flutter:
  assets:
    - assets/

Make a folder assets in root project.

Import:

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';

Add the Audio instances:

AudioCache audioCache = new AudioCache();
AudioPlayer advancedPlayer = new AudioPlayer();

Start the audio:

onPressed: () {audioCache.play('<Audio>.mp3');}

Notification

Dependencies:

dependencies:
  flutter_local_notifications: ^0.5.2
  • Optional: add image inside drawable directory for Notificaiton Icon:

(flutter_app_name) > android > app > src > res > drawable > app_icon.png

Else you can use @mipmap/ic_launcher as default icon.

  • Optional: add audio inside res directory for Notificaiton song:

(flutter_app_name )> android > app > src > res > raw > song.mp3

initialize the Flutter Notification Plugin:

  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  @override
  initState() {
    super.initState();
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('<icon>');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: <ACTION>);
  }

Customize the Notification:

Future showNotification() async {
  var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      'your channel id', 'your channel name', 'your channel description',
      sound: '<sound>', //playSound: false
      importance: Importance.<Importance>,
      priority: Priority.<Priority>);
  var iOSPlatformChannelSpecifics =
  new IOSNotificationDetails(sound: "<sound>"); //presentSound: false
  var platformChannelSpecifics = new NotificationDetails(
      androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
  await flutterLocalNotificationsPlugin.show(
    0,
    '<Notification_Title>',
    '<Notification_desc>',
    platformChannelSpecifics,
    payload: '<Notification_Payload>',
  );
}

Trigger the notification:

onPressed: () => showNotification

Checkout this exemple.

Dialog

Future dialog(String payload) {
  showDialog(
    context: context,
    builder: (_) => new AlertDialog(
      title: new Text('title'),
      content: new Text('content'),
    ),
  );
}

Painting

This class recive an array of points and draw lines between points, the line are characterized by the paint function:

class Painter extends CustomPainter {
  final List<Offset> points;

  Painter(this.points);

  @override
  bool shouldRepaint(Painter oldDelegate) {
    return oldDelegate.points != points;
  }

  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.<color>
      ..strokeCap = StrokeCap.<shape>
      ..strokeWidth = <thick>;

    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i], points[i + 1], paint);
      }
    }
  }
}
  • CustomPainter A widget that provides a canvas on which to draw during the paint phase.
  • Offset Representing a point in Cartesian space a specified distance from a separately-maintained origin.
  • shouldRepaint Called whenever a new instance of the custom painter delegate class is provided to a new CustomPaint object is created with a new instance of the custom painter delegate class.

This Gesture will mark the pan path with as pointes then stored into array, comes under body atrb:

class Paint extends StatefulWidget {
  PaintingState createState() => new PaintingState();
}

class PaintingState extends State<Paint> {
  //This is an array of point that store the tracked pan:
  List<Offset> _points = <Offset>[];

  Widget build(BuildContext context) {
    return new Stack(
      children: [
        GestureDetector(
          onPanUpdate: (DragUpdateDetails details) {
            RenderBox referenceBox = context.findRenderObject();
            Offset localPosition =
                referenceBox.globalToLocal(details.globalPosition);
            setState(() {
              _points = new List.from(_points)..add(localPosition);
            });
          },
          onPanEnd: (DragEndDetails details) => _points.add(null),
        ),
        CustomPaint(painter: new Painter(_points))
      ],
    );
  }
}

Clear the points array:

setState(() => points.clear());

Make an area for painting by calling the Signature().

Checkout this exemple.

Checkout this template

Screen orientation

import: import 'package:flutter/services.dart';

void main() {
  SystemChrome.setPreferredOrientations([DeviceOrientation.<side>,])
      .then((_) {
    runApp(new MyApp());
  });
}

Trigging Area

InkWell A rectangular area of a Material that responds to touch.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // The InkWell Wraps our custom Widget
    return InkWell(
      // When the user taps the Widget
      onTap: (){
        <Action>
        ));
      },
      child: <child>,
    );
  }

Flutter TextField Suggestion

import 'package:flutter/material.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';

import 'model/city_model.dart';
import 'home.dart';

class SearchBar extends StatefulWidget {
  SearchBar({Key key}) : super(key: key);

  @override
  _SearchBar createState() => new _SearchBar(key);
}

//TODO Set the Type should be same as above 
GlobalKey<AutoCompleteTextFieldState<X>> key = new GlobalKey();

class _SearchBar extends State<SearchBar> {
  AutoCompleteTextField searchTextField;

  _SearchBar(Key key);

  Widget row(String city) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(
          city,
          style: TextStyle(fontSize: 16.0),
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Card(
        elevation: 10,
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              //TODO Set the Type 
              searchTextField = AutoCompleteTextField<X>(
                key: key,
                clearOnSubmit: false,
                //TODO Set the data 
                suggestions: X,
                style: TextStyle(color: Colors.black, fontSize: 16.0),
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
                  hintText: "Search Name",
                  hintStyle: TextStyle(color: Colors.black),
                ),
                itemFilter: (item, query) {
                  //If json Set X else remove it
                  return item.X
                      .toLowerCase()
                      .startsWith(query.toLowerCase());
                },
                itemSorter: (a, b) {
                  //If json Set X else remove it
                  return a.X.compareTo(b.X);
                },
                itemSubmitted: (item) {
                  setState(() {
                    //If json Set X else remove it
                    searchTextField.textField.controller.text = item.X;
                  });
                },
                itemBuilder: (context, item) {
                  // ui for the autocomplete row
                  //If json Set X else remove it
                  return row(item.X);
                },
              ),
            ],
          ),
        ));
  }
}

Flutter Cookbook

⚠️ **GitHub.com Fallback** ⚠️