🤝 Provider

Using Provider for state management

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? Let's chat

Open Discord