How to use a Provider in Flutter: Simplest Example

Provider Example in Flutter






Varanasi Software Junction: Flutter Provider













Here is the full code

1. Run the app from inside a MultiProvider
void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => VsjBank()),
      ],
      child: const VsjApp(),
    ),
  );
}
2. The provider will be a class that is with the ChangeNotifier mixin.
We call the notifyListeners() function whenever the state needs updating.

class VsjBank with ChangeNotifier {
  final Account _balance = Account();

  Account get balance => _balance;

  void deposit() {
    _balance.balance += 10;
    _balance.nooftransactions += 1;
    notifyListeners();
  }

  void withdraw() {
    _balance.balance -= 5;
    _balance.nooftransactions += 1;
    // notifyListeners();
  }

  void notify() {
    notifyListeners();
  }
}



3. Next make a class that has the elements whose state you want to manage.
class Account {
  int nooftransactions = 0, balance = 0;
  @override
  String toString() {
    return balance.toString();
  }
}
We have already added this to the ChangeNotifier. Look up the previous entry.


class Account {
  int nooftransactions = 0, balance = 0;
  @override
  String toString() {
    return balance.toString();
  }
}


4. Show the details on a stateless widget.

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

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Balance ${context.watch<VsjBank>().balance.balance}'),
        Text(
            'Transactions ${context.watch<VsjBank>().balance.nooftransactions}'),
      ],
    );
  }
}

5. Show the widgets wherever you want.


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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Vsj Provider Demo'),
          centerTitle: true,
          backgroundColor: Colors.teal,
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Card(
                  child: Text(
                'Account Details',
                style: TextStyle(fontWeight: FontWeight.bold),
              )),
              const AccountManager(),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  onPressed: () => context.read<VsjBank>().deposit(),
                  child: const Text('\nDeposit\nCalls notify\n'),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  onPressed: () => context.read<VsjBank>().withdraw(),
                  child: const Text('\nWithdraw\nNo notify\n'),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  onPressed: () => context.read<VsjBank>().notify(),
                  child: const Text('\nOnly Notify\n'),
                ),
              ),
              const Card(
                  child: Text(
                'Account Details Repeat',
                style: TextStyle(fontWeight: FontWeight.bold),
              )),
              const AccountManager(),
            ],
          ),
        ),
      ),
    );
  }
}


6. Call NotifyListeners wherever required.











import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => VsjBank()),
],
child: const
VsjApp(),
),
);
}

class VsjBank with ChangeNotifier {
final Account _balance = Account();

Account get balance = > _balance;

void deposit() {
_balance.balance += 10;
_balance.nooftransactions += 1;
notifyListeners();
}

void withdraw() {
_balance.balance -= 5;
_balance.nooftransactions += 1;
// notifyListeners();
}

void notify() {
notifyListeners();
}
}


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

);

@override


Widget
build(BuildContext
context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const
Text('Vsj Provider Demo'),
centerTitle: true,
backgroundColor: Colors.teal,
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: < Widget > [
const Card(child: Text('Account Details', style:TextStyle(fontWeight: FontWeight.bold), )),
const
AccountManager(),
Padding(
padding: const
EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () = > context.read < VsjBank > ().deposit(),
child: const
Text('\nDeposit\nCalls notify\n'),
),
),
Padding(
padding: const
EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () = > context.read < VsjBank > ().withdraw(),
child: const
Text('\nWithdraw\nNo notify\n'),
),
),
Padding(
padding: const
EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () = > context.read < VsjBank > ().notify(),
child: const
Text('\nOnly Notify\n'),
),
),
const
Card(child: Text('Account Details Repeat', style:TextStyle(fontWeight: FontWeight.bold), )),
const
AccountManager(),
],
),
),
),
);
}
}

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

);

@override


Widget
build(BuildContext
context) {
return Column(
children: [
Text(

'Balance ${context.watch<VsjBank>().balance.balance}'),
Text(

'Transactions ${context.watch<VsjBank>().balance.nooftransactions}'),
],
);
}
}

class Account {
int nooftransactions = 0, balance = 0;
@ override
String toString() {


return balance.toString();
}
}









Git Repository for this App


Contact us for software training, education or development










 

Post a Comment

0 Comments