deepak singh
deepak singh

Reputation: 1

Problem in updating the state in flutter cubit

PROBLEM : Let say if i type "o" on search input it gives is correct filtered input based on this also if i put "on" it again gives me correct result but when i put "o" again it gives me the result from the state of "on" not from "o" so basically it is working only in forward not in backward updates.

Other things are fine just the state problem

SAMPLE : when typed "o" : state is => "one", "only", "two", "five" filteredState is => "one", "only", "two" when typed "on" : state is => "one", "only", "two", "five" filteredState is => "one", "only" when backpressed to "o" : state is => "one", "only" filteredState is => "one", "only"

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:notecraft/data/models/note_model.dart';

class NoteCubit extends Cubit<List<Note>> {
  NoteCubit() : super([]);

  void addNote(Note note) {
    emit([...state, note]);
  }

  void emitAllNotes() {
    emit(state);
  }

  List<Note>? getAllNotes() {
    return state;
  }

  Note? getNote(int id) {
    for (Note note in state) {
      if (note.id == id) {
        return note;
      }
    }
    return null;
  }

  void getOneNote(int id) {
    emit(state
        .where((parseNote) => parseNote.id == id)
        .map((parseNote) => parseNote)
        .toList());
  }

  void updateNote(Note note) {
    emit(state.map((parseNote) {
      if (parseNote.id == note.id) {
        return parseNote.copyWith(
          title: note.title,
          description: note.description,
          updated_at: '22-jan-2024',
        );
      }
      return parseNote;
    }).toList());
  }

  void restoreNote(Note note) {
    emit(state.map((parseNote) {
      if (parseNote.id == note.id) {
        return parseNote.copyWith(isDeleted: 0);
      }
      return parseNote;
    }).toList());
  }

  void deleteNote(int id) {
    emit(state.where((parseNote) => parseNote.id != id).toList());
  }

  void searchNote(String query) {
    if (query.isEmpty) {
      print("@@@@@@@@@@@@@@@@@  EMPTY STATE");
      for (Note note in state) {
        print(note.title + "@@@@@@@@@@@@@@@@@@@@@@@@ ");
      }
      emit(List<Note>.from(state));
      return;
    }
    print("============== QUERY : " + query + "=======================");

    List<Note> filterState = state
        .where((note) =>
            note.title.toLowerCase().contains(query.toLowerCase()) ||
            note.description.toLowerCase().contains(query.toLowerCase()))
        .toList();

    for (Note note in state) {
      print(note.title + "******************** ");
    }
    emit(filterState);
  }
}

searchNote

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:notecraft/data/cubit/note_cubit.dart';

class SearchInput extends StatefulWidget {
  const SearchInput({super.key});

  @override
  State<SearchInput> createState() => _SearchInputState();
}

class _SearchInputState extends State<SearchInput> {
  late final NoteCubit noteCubit;

  @override
  void initState() {
    noteCubit = BlocProvider.of<NoteCubit>(context);
    super.initState();
  }

  void searchNotes(String query) {
      noteCubit.searchNote(query);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 340,
        height: 50,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(
            90,
          ),
          border: Border.all(
            color: Colors.amber,
            width: 2.0,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            const SizedBox(
              width: 10,
            ),
            const Icon(Icons.search),
            SizedBox(
              height: 50,
              width: 280,
              child: TextField(
                onChanged: (value) {
                  searchNotes(value);
                },
                decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: "Search form your notes",
                ),
              ),
            )
          ],
        ));
  }
}

Display of state note

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:notecraft/common/display_cards/note_card.dart';
import 'package:notecraft/data/cubit/note_cubit.dart';
import 'package:notecraft/data/models/note_model.dart';

class NotesScreen extends StatefulWidget {
  final int isDeleted;
  const NotesScreen({super.key, required this.isDeleted});

  @override
  State<NotesScreen> createState() => _NotesScreenState();
}

class _NotesScreenState extends State<NotesScreen> {
  @override
  Widget build(BuildContext context) {
    final noteCubit = BlocProvider.of<NoteCubit>(context);

    return BlocBuilder<NoteCubit, List<Note>>(
      bloc: noteCubit,
      builder: (context, notes) {
        final activeNotes =
            notes.where((note) => note.isDeleted == widget.isDeleted).toList();
        return Padding(
          padding: const EdgeInsets.all(16.0),
          child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 8.0,
              mainAxisSpacing: 8.0,
            ),
            itemCount: activeNotes.length,
            itemBuilder: (context, index) {
              return NoteCard(
                isDeleted: widget.isDeleted,
                note: activeNotes[index],
              );
            },
          ),
        );
      },
    );
  }
}

the problem is in searchNote functionality when i am printing state in else part it is working good the correct state is printing but when i am printing the if part the state which is filtered is printing not the original state i.e original state is getting modified in filterState

Upvotes: 0

Views: 38

Answers (0)

Related Questions