Flutter provider ChangeNotifierProxyProvider example

provider is a Flutter library for state management. This post demonstrates how to use provider’s ChangeNotifierProxyProvider for sharing data between 2 providers, and using the data from one provider in another provider.

1. Here are 2 providers, Person and Job. Job depends on Person, meaning Job will be using the data from Person.

class Person with ChangeNotifier {
  Person({required this.name, required this.age});

  final String name;
  int age;

  void increaseAge() {
    age++;
    notifyListeners();
  }
}

class Job with ChangeNotifier {
  Job(this.person);

  String career = "na";
  Person person;

  setPerson(Person p) {
    person = p;
    notifyListeners();
  }

  addCareer(value) {
    career = value;
    notifyListeners();
  }

  String get title {
    return '${person.name}, $career, ${person.age}';
  }
}

2. Initialize the providers with ChangeNotifierProxyProvider as the following. Inside the ChangeNotifierProxyProvider, create for creating the initial Job provider, update for updating the person within the job when there is an update.

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => Person(name: 'John', age: 22)),
        ChangeNotifierProxyProvider(
          create: (BuildContext context) => Job(Provider.of(context, listen: false)),
          update: (BuildContext context, Person person, Job? job) {
            job?.setPerson(person);
            return job ?? Job(person);
          }
        ),
      ],
      child: const MyApp(),
    ),
  );
}

3. The initState function that initializes the career field in the job provider. initState() is a method of class State and it is considered as an important lifecycle method in Flutter. initState() is called the only once and we use it for one-time initializations

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

  final job = Provider.of(context, listen: false);
  job.addCareer("Accountant");
}

4. Update the age in the Person provider to increase the age.

context.read().increaseAge();

5. Get the title from Job provider. Initially, the age was initialized with 22 in the above example, after calling the code in step 4, it becomes 23, and it should show 23 when the following print statement is executed.

String title = context.watch().title;
print("title: $title");

Search within Codexpedia

Custom Search

Search the entire web

Custom Search