...

/

Application of ChangeNotifier With Provider

Application of ChangeNotifier With Provider

Learn about the native Flutter ChangeNotifier class and how to use it with the Provider library in a working app.

We will build a quiz app using a StatelessWidget, Provider, and ChangeNotifier. We will view this whole application at the end of this lesson.

Reducing widget rebuilds

The code snippet below is fairly long so let us break it down to understand how it works.

We keep the Providers above the app. Although it has a different reason involving the test purpose, it still has another advantage.

As already mentioned, Provider is the wrapper class of the inherited widget.

Here is the main method, the entry point of our app.

Press + to interact
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'remodelled-quiz-app/model/question_and_answer_model.dart';
import 'remodelled-quiz-app/view/new_quiz_app.dart';
void main() {
runApp(
/// Providers are above [MyApp] instead of inside it, so that tests
/// can use [MyApp] while mocking the providers
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => QuestionAndAnswerModel()),
],
child: NewQuizApp(),
),
);
}

We have already created three directories: controller, model, and view. We will keep our NewQuizApp widget in the view directory.

Press + to interact
import 'package:flutter/material.dart';
import 'new_quiz_app_home.dart';
class NewQuizApp extends StatelessWidget {
const NewQuizApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: NewQuizAppHome(),
);
}
}

The ...