DEV Community

Cover image for Sneak Peak into Flutter State management #1
Arjun Kohli
Arjun Kohli

Posted on • Updated on

Sneak Peak into Flutter State management #1

Hello awesome people, this is an introduction to flutter where we will look into various built in classes and widgets offered by Flutter development team which comes in handy while developing modular cross platform apps with flutter.

So at first we will understand the arrangement of various widgets in flutter in a representative structure known as the Flutter widget tree.
Widget tree in Flutter
Each renderable element on a screen of the Flutter app is a widget,these widgets together combine to form a widget tree in flutter.
The widget tree is how developers create their user interface; developers position widgets within each other to build simple and complex layouts.

A Flutter app is all about the state management and if you are confused as to what the state management is no worries I'll define it for you before getting any further.
State management refers to as to how the widgets rebuilds themselves according the latest changes behind the scene so as to keep the user updated and let them interact with the application.

Let's now dive into the main crux of this article , the various built in classes and widgets provided by flutter for state management .

1)Futures in Flutter
When a function returns a Future, it means that it takes a while for its result to be ready, and the result will be available in the future.
Calling a function that returns a Future, will not block your code, that’s why that function is called asynchronous. Instead, it will immediately return a Future object, which is at first uncompleted.The result of the Future is available only when the Future is completed.
It is similar to ‘Promises’ in javascript and emits only a single value once.

Future<String> _getValue() async { 
await Future.delayed(Duration(seconds:5));
return "Hello world";
 }

Enter fullscreen mode Exit fullscreen mode

2)Future builder in flutter

Future builder takes in two argument one being “future” which takes in the future function to be called and other being “builder” which rebuilds the widget in the widget tree according to the latest value of future object stored in snapshot.

Example:-

FutureBuilder<String>(
        future: _getValue, // async work
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
           switch (snapshot.connectionState) {
             case ConnectionState.waiting: return Text('Loading....');
             default:
               if (snapshot.hasError)
                  return Text('Error: ${snapshot.error}');
               else
              return Text('Result: ${snapshot.data}');
            }
         },
        ),

Enter fullscreen mode Exit fullscreen mode

3)Callbacks to parent widget from child widget
There are callback functions defined in flutter for communication between widgets up the widget tree (from child to parent).For instance if you have a button labelled “Increment” which increments the value of counter displayed in the parent widget of which the button is a part(child widget) for this purpose we will send a call back each time the button is hit from child to parent.

Example:-

import 'package:flutter/material.dart';

// Step 1: Define a Callback in child widget.
typedef void IntCallback(int id);

class Child extends StatelessWidget {
  final IntCallback callBackValue;
  Child({ @required this.callBackValue });
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      onPressed: () {
        callBackValue(1);
      },
      child: Text('Click me to increment value!'),
    ),
  }
}
Enter fullscreen mode Exit fullscreen mode
///
/// Inside the Parent Widget
///
import 'package:flutter/material.dart';

class Parent extends StatefulWidget {
  @override
  _Parentstate createState() => _Parentstate();
}

class _Parentstate extends State<Parent> {
int parentValue=0;

  @override
  Widget build(BuildContext context) {
    return Column(

      children:[ 
               Child(callBackValue:(valueFromChild)=>
setState((){parentValue=parentValue+valueFromChild;}),

             Text("Press the button to change value to 1:$parentValue")]
//As soon as the button is pressed value 0 will increment by 1 each time.
      )
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Apart from this communication between widgets down the tree is quite easy(from parent to child) simply pass the data from parent to child as arguments.


class Child extends StatelessWidget {
  final String valueFromParent;
  Child({ @required valueFromParent });
  //...  
@override
  Widget build(BuildContext context) {
return Text("The value passed from parent widget is:$valueFromParent"
}
}
Enter fullscreen mode Exit fullscreen mode
class Parent extents StatelessWidget{
 @override
  Widget build(BuildContext context) {
return Child(valueFromParent:"Hello world")
}}

Enter fullscreen mode Exit fullscreen mode

So this much it for this article , part 2 of this article covers further information about reactive programming in flutter including Streams, StreamBuilder, Value Notifiers, ValueListenableBuilder and so.
Thanks for having a read and getting down till here .Have a great development day ahead.
Link for the same is attached below:
https://dev.to/arjun3492/sneak-peak-into-flutter-state-management-2-1abn

Top comments (0)