Tuesday, June 6, 2023

Efficient Flutter CRUD App with Provider State Management

 Streamline your app development with this Flutter CRUD app powered by the Provider state management tool. Seamlessly create, read, update, and delete data while maintaining efficient state management. Simplify your development process and enhance user experiences with this powerful combination of Flutter and Provider.

Here's an example of a Flutter CRUD app using the Provider package for state management:

First, make sure you have the Provider package added to your pubspec.yaml file:

dependencies: flutter: sdk: flutter provider: ^6.0.1 
 

Next, create a new Flutter project and replace the contents of the main.dart file with the following code:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => TodoProvider(),
      child: MaterialApp(
        title: 'Flutter CRUD App',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: TodoListScreen(),
      ),
    );
  }
}

class Todo {
  String id;
  String title;
  String description;

  Todo({
    required this.id,
    required this.title,
    required this.description,
  });
}

class TodoProvider with ChangeNotifier {
  List<Todo> todos = [];

  void addTodo({
    required String title,
    required String description,
  }) {
    final newTodo = Todo(
      id: DateTime.now().toString(),
      title: title,
      description: description,
    );
    todos.add(newTodo);
    notifyListeners();
  }

  void updateTodo({
    required String id,
    required String title,
    required String description,
  }) {
    final todoIndex = todos.indexWhere((todo) => todo.id == id);
    if (todoIndex >= 0) {
      todos[todoIndex] = Todo(
        id: id,
        title: title,
        description: description,
      );
      notifyListeners();
    }
  }

  void deleteTodo({
    required String id,
  }) {
    todos.removeWhere((todo) => todo.id == id);
    notifyListeners();
  }
}

class TodoListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final todoProvider = Provider.of<TodoProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Todo List'),
      ),
      body: ListView.builder(
        itemCount: todoProvider.todos.length,
        itemBuilder: (context, index) {
          final todo = todoProvider.todos[index];
          return ListTile(
            title: Text(todo.title),
            subtitle: Text(todo.description),
            trailing: IconButton(
              icon: Icon(Icons.delete),
              onPressed: () {
                todoProvider.deleteTodo(id: todo.id);
              },
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => TodoFormScreen(),
            ),
          );
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class TodoFormScreen extends StatefulWidget {
  @override
  _TodoFormScreenState createState() => _TodoFormScreenState();
}

class _TodoFormScreenState extends State<TodoFormScreen> {
  final _formKey = GlobalKey<FormState>();
  late String _title;
  late String _description;

  @override
  Widget build(BuildContext context) {
    final todoProvider = Provider.of<TodoProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Add Todo'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Title',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter a title';
                  }
                  return null;
                },
                onSaved: (value) {
                  _title = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Description',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter a description';
                  }
                  return null;
                },
                onSaved: (value) {
                  _description = value!;
                },
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    _formKey.currentState!.save();
                    todoProvider.addTodo(
                      title: _title,
                      description: _description,
                    );
                    Navigator.pop(context);
                  }
                },
                child: Text('Add Todo'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

This example demonstrates a simple CRUD (Create, Read, Update, Delete) app using 

Provider for state management. The TodoProvider class manages the state and contains 

functions for adding, updating, and deleting todos. The TodoListScreen displays the list 

of todos and allows users to delete items. The TodoFormScreen provides a form for adding 

new todos.

 

To run this app, make sure you have Flutter and Dart installed on your machine. Then 

create a new Flutter project, replace the contents of the main.dart file with the provided 

code, and run the app using flutter run.

 

Note: This is a basic example to get you started with CRUD operations using Provider. 

You can further enhance the app by adding edit functionality, persisting data, and 

implementing more advanced features based on your requirements.

 

 

 

No comments:

Post a Comment

Enhancing Flutter Apps with BLoC State Management and REST APIs for Optimal Performance

 Develop a powerful Flutter app utilizing BLoC state management and REST APIs to enhance functionality and performance. Flutter app using th...