I have been learning About Flutter for some time, and I came across that everyone talked about state management. Most people use Redux. As an Android developer, I have never been familiar with Flutter before, so I started to learn about Redux. After that, I learned about fish_redux launched by Xianyu. Then I saw a series of articles about Flutter state management published by Vadaski, including Scoped Model, Redux, BLoC,RxDart and provide (you can move to know more about them), which made me dazzled. As for Redux, I can understand how to write it, but when it comes to the application level, I still feel a bit difficult. I don’t know how to maintain it well, and I don’t know what to use for myself at that time. Later, I came into contact with the Provider recommended by Google, so I learned it. Let’s use a Provider to implement an example of counting.

The first step is to add the Provider dependency

The provider: ^ 2.0.1 + 1Copy the code

Dev /packages/pr…

Step 2, create the Model

import 'package:provider/provider.dart';
class Counter with ChangeNotifier {//1
  int _count;
  Counter(this._count);

  void add() { _count++; notifyListeners(); //2 } get count => _count; / / 3}Copy the code

A simple Counter object with only one field, _count

  1. So here we have to mixChangeNotifier
  2. Write an increment method that needs to be callednotifyListeners();This method is used for notificationsCounterObject for the widget refresh.
  3. getmethods

Step 3: UseChangeNotifierProvider

Usually the main() method is written like this

main() {
  runApp(MyApp());
}
Copy the code

To listen for changes, we need to put a layer around MyApp(), which is global, so it looks like this

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

main() {
  runApp(ChangeNotifierProvider<Counter>.value(//1
    notifier: Counter(1),//2
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: "Provider", home: HomePage(), ); }}Copy the code
  1. ChangeNotifierProvidercallvalue()Method, from insidenotifierandchild
  2. notifierI set the default Counter(1)

Of course Provider not only provides ChangeNotifierProvider, and the Provider, ListenableProvider, ValueListenableProvider, StreamProvider, specific we can see the wiki. If you want to manage multiple objects, you can use MultiProvider as follows

MultiProvider( providers: [ Provider<User>.value(value: user), Provider<Goods>.value(value: goods), ..... ] , child: someWidget, )Copy the code

Step 4, use the Provider to get the value of Counter

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
        actions: <Widget>[
          FlatButton(
            child: Text("Next page"),
            onPressed: () =>
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return SecondPage();
                })),
          ),
        ],
      ),
      body: Center(
        child: Text("${Provider.of<Counter>(context).count}"),//1
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Counter>(context).add();//2
        },
        child: Icon(Icons.add),
      ),
    );
  }
}
Copy the code
  1. withProvider.of<Counter>(context).countTo obtain_countThe value of theProvider.of<T>(context)Equivalent to the Provider finding what it managesCounter(1)
  2. withProvider.of<Counter>(context).add();callCounter()In theadd()methods

Do the same for the second page, as follows

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("SecondPage"),
      ),
      body: Center(
        child: Text("${Provider.of<Counter>(context).count}"),//1
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Counter>(context).add();//2
        },
        child: Icon(Icons.add),
      ),
    );
  }
}
Copy the code

This way, when the + button is clicked on every page, _count +1 is notified and updated to where it is used.

Complete code, copy can be run directly

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

main() {
  runApp(ChangeNotifierProvider<Counter>.value(
    notifier: Counter(1),
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: "Provider",
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
        actions: <Widget>[
          FlatButton(
            child: Text("Next page"),
            onPressed: () =>
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return SecondPage();
                })),
          ),
        ],
      ),
      body: Center(
        child: Text("${Provider.of<Counter>(context).count}"),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Counter>(context).add();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(Provider.of<String>(context)),
      ),
      body: Center(
        child: Text("${Provider.of<Counter>(context).count}"),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Counter>(context).add();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class Counter with ChangeNotifier {

  int _count;

  Counter(this._count);

  void add() {
    _count++;
    notifyListeners();
  }

  get count => _count;
}
Copy the code

conclusion

After reading so much about state management, I feel that Provider is still easy to use and recommended by Google. But I feel like I need to grow up and be recognized. I only use Flutter briefly here. Please forgive me for not being too clear in some places. At the same time, I also hope to communicate and make progress with students studying Flutter.