This example demonstrates how to use the Provider package for state management in a Flutter app.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Provider Example',
theme: ThemeData(primarySwatch: Colors.blue),
home: CounterScreen(),
);
}
}
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
void decrement() {
_count--;
notifyListeners();
}
}
class CounterScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: ${context.watch<Counter>().count}'),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => context.read<Counter>().decrement(),
child: Text('-'),
),
SizedBox(width: 20),
ElevatedButton(
onPressed: () => context.read<Counter>().increment(),
child: Text('+'),
),
],
),
],
),
),
);
}
}
Leave a Reply