Search⌘ K
AI Features

Challenge: A Basic Provider-Based Application

Explore how to create a basic Flutter application using Provider to handle state management without stateful widgets. Learn to implement a counter that increments on button press and validate if a text message starts with a specific letter. This lesson helps you practice applying state management techniques in Flutter for efficient app development.

Problem statement

Create a Flutter application to manage the state through the Provider. Don’t use the stateful widget.

The first challenge is to create a counter where you can increment numbers by pressing the button and changing the state.

The second challenge is to test whether a text message starts with the letter “s” or not.

As a head start, we have already completed the model class for you. You only need to make changes to the controller.dart file.

Expected output

The following image is a sample output. Your app’s output can be slightly different based on your approach, but it should satisfy the entire problem statement.

Test yourself

import 'package:flutter/material.dart';
import 'model/counting_the_number.dart';
import 'view/my_home_page.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    // ChangeNotifierProvider, unlike ChangeNotifier, comes from the Provider package
    // and it provides an instance of a ChangeNotifier to the widgets,
    // which have already subscribed to it
    // we should place the ChangeNotifierProvider Just above the widgets that need to access it.
    // you will understand provider better if you already have understood how
    // InheritedWidget works
    ChangeNotifierProvider(
      create: (context) =>
          CountingTheNumber(), // designed Model is provided to the desired widgets
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'A Basic Provider Application',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
A basic provider-based app