Provider Using Provider for state management

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

Provider is one of the most popular state management libraries in Flutter. It wraps InheritedWidget and provides an easy way to share data between widgets.

1. Define State

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

class CounterState extends ChangeNotifier {

  int count = 0;

  updateCount() {
    count++;
    notifyListeners();
  }

}

2. Provide State

file_type_flutter main.dart
class CounterApp extends StatelessWidget {
  const CounterApp({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return ChangeNotifierProvider(
      create: (context) => CounterState(),
      child: const CountText(),
      
    );
  }
}

3. Read State

file_type_flutter main.dart
class CountText extends StatelessWidget {
  const CountText({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {

    var state = context.watch<CounterState>();
    var state2 = Provider.of<CounterState>(context);

    return Text('${state.count}');
  }
}

Questions?

Ask questions via GitHub below OR chat on Slack #questions