Flutter Provider – Basic and Advanced Example
Flutter is a widely-used UI toolkit that allows developers to build beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. Among the state management solutions available in Flutter, the Provider package stands out due to its simplicity and efficiency.
What is Flutter Provider?
The Provider package is a popular state management solution in Flutter that leverages the concept of inheritedwidget for managing submission state across widgets. By using the Provider package, developers can easily share data among different parts of their application without the hassle of lifting state up.
Benefits of Using Flutter Provider
- Simplicity: Minimal boilerplate code is needed to manage state.
- Performance: Efficient UI updates through selective widget rebuilding.
- Readability: Clean and maintainable code structure.
- Community Support: Popular package with extensive documentation and community resources.
Basic Example of Flutter Provider
Setting Up the Provider Package
First, include the Provider package in your flutter project by adding the dependency in your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0
Creating a Simple Counter App
Let’s create a simple counter application using Provider:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => Counter(),
child: MaterialApp(
home: CounterScreen(),
),
);
}
}
class CounterScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Counter App")),
body: Center(
child: Column(
mainAxisAlignment: mainaxisalignment.center,
children: [
Text('Count: ${Provider.of(context).count}'),
ElevatedButton(
onPressed: () {
Provider.of(context, listen: false).increment();
},
child: Text('Increment'),
),
],
),
),
);
}
}
Advanced Example of Flutter Provider
building a Todo App with Provider
Now let’s advance our knowledge by creating a simple Todo app. We will use Provider to manage our Todo list’s state.
class Todo {
String title;
bool isDone;
Todo({required this.title, this.isDone = false});
}
class TodoProvider with ChangeNotifier {
final List _todos = [];
List get todos => _todos;
void addTodo(String title) {
_todos.add(Todo(title: title));
notifyListeners();
}
void toggleTodoStatus(int index) {
_todos[index].isDone = !_todos[index].isDone;
notifyListeners();
}
}
class TodoApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => TodoProvider(),
child: MaterialApp(
home: TodoScreen(),
),
);
}
}
class TodoScreen extends statelesswidget {
@override
Widget build(BuildContext context) {
var todoProvider = Provider.of(context);
return Scaffold(
appBar: AppBar(title: Text("Todo App")),
body: Column(
children: [
Expanded(child: ListView.builder(
itemCount: todoProvider.todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todoProvider.todos[index].title),
leading: Checkbox(
value: todoProvider.todos[index].isDone,
onChanged: (bool? value) {
todoProvider.toggleTodoStatus(index);
},
),
);
},
)),
TextField(
onSubmitted: (String value) {
todoProvider.addTodo(value);
},
decoration: InputDecoration(labelText: "add Todo"),
),
],
),
);
}
}
Practical Tips for Using Flutter Provider
- Keep your classes clean: Separate your data models and providers for better organization.
- Use multi-provider: For larger applications, consider using
MultiProvider
to manage multiple states comfortably. - Optimize rebuilds: Use the
Select
method to optimize the rebuild process for your widgets. - Leverage Consumer Widget: The
Consumer
widget allows selective listening and builds only when ther’s a state change.
Case Studies: Triumphant Implementations
App Name | Framework | State Management solution |
---|---|---|
MyWeather | Flutter | Provider |
Todoo | Flutter | GetX |
Finance Tracker | Flutter | Provider |
Conclusion
Incorporating the Flutter Provider package into your application not only streamlines state management but also enhances code maintainability and performance. Whether you’re building a basic counter app or a more complex Todo application,the Provider package empowers you with the tools to effectively manage state. By following best practices, leveraging advanced features, and optimizing your usage of the Provider package, you can create dynamic, responsive applications that engage users while keeping the codebase clean and efficient.
Start exploring the capabilities of the Flutter Provider today, and elevate your app development experience!
RELATED POSTS
View all