Flutter Advance - splimter/Flutter GitHub Wiki

Flutter Advance

Deep Understanding Flutter -Widget — State — BuildContext — InheritedWidget.

  • A BuildContext is nothing else but a reference to the location of a Widget within the tree structure of all the Widgets which are built. They are chained and are composing a tree of BuildContexts (parent-children relationship).

Widgets are of 2 types:

  • StatelessWidget These Widgets will not have to care about any variation, once created.
    • The lifecycle: initialization && build().
class Widget extends StatelessWidget{
  Widget build(BuildContext context) {
    return <...>;
  }
}
  • Stateful Widget Some other Widgets will handle some inner data that will change during the Widget’s lifetime. This data hence becomes dynamic.
    • The lifecycle: initState(), build(), && dispose().
class Widget extends StatefulWidget {
  createState() {
    return WidgetState();
  }
}

class WidgetState extends State<Widget> {
  Widget build(context) {
    return <...>;
  }
}

The set of data held by this Widget and which may vary during the lifetime of this Widget is called a State.

Any changes which is applied to a State forces the Widget to rebuild.

A State is linked to one BuildContext and a BuildContext is linked to an instance of a Widget.

  • The [InheritedWidget](https://medium.com/flutter-community/widget-state-buildcontext-inheritedwidget-898d671b7956#5fad) is a special Widget, that you put in the Widgets tree as a parent of another sub-tree. All widgets part of that sub-tree will have to ability to interact with the data which is exposed by that InheritedWidget.

BLOC Pattern

Its a state management system for Flutter recommended by Google developers. It helps in managing state by using STREAMS or REACTIVE approach. In general terms, data will be flowing from the BLOC to the UI or from UI to the BLOC in the form of streams, and make access of data from a central place in your project.

We use bloc instead of StateFullWidgets to share information around our app

import 'dart:async'; Support for asynchronous programming, with classes such as Future and Stream.

StreamController<T> This controller allows sending data, error and done events on its stream. This class can be used to create a simple stream that others can listen on, and to push events to that stream.

Stream<T> A Stream provides a way to receive a sequence of events. Each event is either a data event, also called an element of the stream, or an error event, which is a notification that something has failed.

EventSink<T> This makes it suitable for capturing the results of asynchronous computations, which can complete with a value or an error.

StreamTransformer<S, T> To control the processing of data inside a Stream.

Stream<S> transform <S>(StreamTransformer<T, S> streamTransformer) Applies streamTransformer to this stream.

Quick example

Make a data modle:

import 'dart:async';

import 'package:flutter/cupertino.dart';

class Bloc extends ChangeNotifier  {

  String _wind = "";

  String get wind => _wind;

  // for validation
  apply(){
    notifyListeners();
  }
}

Wrape main Widget:

ChangeNotifierProvider<Bloc>(
  builder: (_) => Bloc(),
  child: Home(),
),

To set Data:

...
@override
  Widget build(BuildContext context) {
    final blocModel = Provider.of<Bloc>(context);
    ....
    //Always better use the apply function
    blocModel.apply();

To get Data:

Widget build(BuildContext context) {
  final blocModel = Provider.of<Bloc>(context);
  ...
  Text(blocModel.wind),

RXDart

RxDart is an implementation of the popular reactiveX api for asynchronous programming, leveraging the native Dart Streams api.

add rxdart: ^0.16.7 as dependencies.

Observable<T> A wrapper class that extends Stream. It combines all the Streams and StreamTransformers contained in this library into a fluent api.

combineLatest2<A, B, T> Merges the given Streams into one Observable sequence by using the combiner function whenever any of the observable sequences emits an item.

BehaviorSubject<T> A special StreamController that captures the latest item that has been added to the controller, and emits that as the first item to any new listener

Stream Exemple

Making a Validator:

final <var> =
	StreamTransformer<T, T>.fromHandlers(handleData: (<data>, sink) {
		if (<validat_condition>)
			sink.add(<data>);
		else
			sink.addError('msg');
});

Add data to Stream in bloc:

Stream<T> get <varS> => <privateVar>.stream.transform(<validatorName>);

When the data change:

Function(T) get <varC> => <privateVar>.sink.add;

Widgets use StreamBuilders to change their contents depending on values coming a stream.

can be used:

stream: <bloc>.<varS>,
.
.
onChanged:  <bloc>.<varC>,

Checkout this exemple.

Build Your App

flutter build appbundle
flutter build apk --split-per-abi

For more detail check the main docs

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