Dart4Flutter – 01 — Variables, types, and functions

Dart4Flutter — 02 — Control flow and anomalies

Dart4Flutter — 03 — Classes and generics

Dart4Flutter — 04 — async and library

Dart 4FLUTTER – gLEANer 01 – Flutter – DART environment setup

Dart4Flutter – immutability

Flutter Entry – State management

Introduction to Flutter Example 1

Description about the properties of Flutter Container

Flutter Entry – Local access -MethodChannel

Flutter instance – Load more ListViews

Flutter instance – Local to Flutter communication – Event Channels

Flutter is a new cross-platform framework developed using the Dart language. Moving to a new platform, there is one problem: state management.

  • How do you pass state down the component
  • How do I refresh the UI when the state changes
  • How to jump between different interfaces and synchronize state

start

Since we are going to demonstrate jumping between different screens, we now create two files myhomepage.dart and mySecondPage.dart.

Our examples are as follows:

  • Increment the value of counter in MyHomePage
  • Jump to MySecondPage.
  • Reduce the value of counter on the MySecondPage screen.

It seems simple enough, but we need to find a way to synchronize the counter between the two screens.

Let’s say now counter=0; When we increase counter to 2 in MyHomePage and then jump to MySecondPage, counter must also be displayed as 2.

At the same time, if we decist counter twice on MySecondPage, when the user jumps to MyHomePage, counter should also be 0.

This is state management.

Assume you already know the setState() mechanism, the mechanism used to update the UI. Now let’s see what we can do.

The main. The dart is as follows:

import 'package:flutter/material.dart';
import 'package:flutter_redux_example/screens/MyHomePage.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
  
  @override
  _MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
  int counter;
  @override
  void initState() {
    super.initState();
    counter = counter ?? 0;
  }
  void _decrementCounter(_) {
    setState(() {
      counter--;
      print('decrement: $counter');
    });
  }
  
  void _incrementCounter(_) {
    setState(() {
      counter++;
      print('increment: $counter');
    });
  }
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(
        title: 'My Home Page', counter: counter, decrementCounter: _decrementCounter, incrementCounter: _incrementCounter, ), ); }}Copy the code

As shown above, _decrementCounter() and _incrementCounter() are methods for incrementing and decrementing counter, respectively, and we use them as constructors for MyHomePage.

MyHomePage. Dart is as follows:

import 'package:flutter/material.dart';
import 'package:flutter_redux_example/screens/MySecondPage.dart';
class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key key,
    this.title,
    this.counter,
    this.decrementCounter,
    this.incrementCounter
  }) : super(key: key);
  final String title;
  final int counter;
  final ValueChanged<void> decrementCounter;
  final ValueChanged<void> incrementCounter;
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  void _onPressed() {
    widget.incrementCounter(null);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('You have pushed the button this many times:'),
            new Text(
              widget.counter.toString(),
              style: Theme.of(context).textTheme.display1,
            ),
            new RaisedButton(
              child: new Text('Next Screen'),
              onPressed: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(
                    builder: (context) => new MySecondPage(
                      widget.decrementCounter,
                      title: 'My Second Page',
                      counter: widget.counter,
                    ),
                  ),
                );
              },
            )
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _onPressed,
        tooltip: 'Increment',
        child: newIcon(Icons.add), ), ); }}Copy the code

As shown above, we pass decrementCounter() down as an argument to the MySecondPage constructor.

The mysecondPage.dart file looks like this:

import 'package:flutter/material.dart';

class MySecondPage extends StatefulWidget {
  MySecondPage(
    this.decrementCounter, 
    {Key key, this.title, this.counter}
  ): super(key: key);
  final String title;
  final int counter;
  final ValueChanged<void> decrementCounter;
  @override
  _MySecondPageState createState() => new _MySecondPageState();
}
class _MySecondPageState extends State<MySecondPage> {
  void onPressed() {
    widget.decrementCounter(null);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('You have pushed the button this many times :'),
            new Text(
              super.widget.counter.toString(),
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
    floatingActionButton: new FloatingActionButton(
      onPressed: onPressed,
      tooltip: 'Decrement',
      child: newIcon(Icons.indeterminate_check_box), backgroundColor: Colors.red), ); }}Copy the code

conclusion

This is easier to understand if you know React.

The StatefulWidget and StatelessWidget in flutter correspond to the Component and PureComponent in React. What is called a Widget in a flutter and a React is called a Component

reference

  • medium.com/@agungsurya…
  • Github.com/brianegan/f…
  • Github.com/brianegan/f…