Search⌘ K
AI Features

Application of ChangeNotifier With Provider

Explore how to implement ChangeNotifier with the Provider package in Flutter to build a quiz app. Understand state changes, avoid unnecessary widget rebuilds, and manage app state effectively using best practices.

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.

Dart
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.

Dart
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 ...