State Management with provider Flutter – P1


1.Tạo project:

flutter create state_provider_demo

2.Setup provider:

flutter pub add provider

3.Import package provider:

import 'package:provider/provider.dart';

4.Code
ChangeNotifer là một lớp trong Flutter SDK cung cấp API thông báo thay đổi. Vì vậy ChangeNotifier chứa 1 method called notifyListener(), bất cứ khi nào nó được gọi, nó sẽ thông báo cho tất cả các khách hàng đã đăng ký với nó rằng đối tượng đã thay đổi. Hãy xem trong ví dụ bên dưới:
Thêm code sau:


class CounterViewModel extends ChangeNotifier {

  int _counter = 0;

  int get counter => _counter;

    void incrementCounter() {
      _counter++;
      notifyListeners();
  }
}

Vì vậy, ở đây chúng tôi tạo một lớp có tên là CounterViewModel which will extend the ChangeNotifier class to be able to use the notifyListener() method, hoặc chúng ta có thể sử dụng nó như một lớp mixin CounterViewModel with ChangeNotifier { in both cases we have access to the notifyListener() method. We use the incrementCounter method to add +1 to the _counter variable. When the _counter changes, the class will notify its listener using notifyListeners(). Now, navigate to the main.dart file and add the following:


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (BuildContext context) =>  CounterViewModel(),
        child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        ));
  }
}

So here, instead of using the Provider widget, we use ChangeNotifierProvider which will listen to changes in the CounterViewModel and update the UI. Then inside the home_screen.dart, we do the following:

There are few similarities that you need to know
final model = context.read() This returns the Model without listening for any changes.
final model = context.watch() This makes the widget listen for changes on the Model.
final model = Provider.of(context, listen: false) This works the same as context.read();
final model = Provider.of(context) This works the same as context.watch();
Code similarities no use Consumer :

context.watch<CounterViewModel>().counter
Provider.of<CounterViewModel>(context).counter
Provider.of<CounterViewModel>(context,listen: false).incrementCounter
context.read<CounterViewModel>().incrementCounter

Link tham khảo:
https://davidserrano.io/flutter-state-management-made-easy-with-provider-flutter-tutorial-for-beginners
https://petercoding.com/flutter/2021/07/11/using-provider-in-flutter/

Full code