cubit возвращает нулевое значение

#flutter #bloc #flutter-bloc

Вопрос:

Я столкнулся с очень странной проблемой. я использую блок с замороженным, инъекционным и dartz. мне просто нужно получить данные из базы данных SQl и отобразить их при открытии страницы «Сегодня».

Код пользовательского интерфейса является:

 class TodayPage extends HookWidget {
  const TodayPage();
  @override
  Widget build(BuildContext context) {
    return BlocProvider<ScheduledNotesCubit>(
      lazy:false,
      create: (context) => getIt<ScheduledNotesCubit>()
        ..countDoneNoteOutOfAllNotes()
        ..retrieveData(),
      child: BlocBuilder<ScheduledNotesCubit, ScheduledNotesState>(
        builder: (context, state) {
          return ListView.builder(
            itemCount: state.maybeMap(
                orElse: () {}, getNotesCount: (g) => g.noteCount),
            itemBuilder: (BuildContext context, int index) {
            return  Text(
                "${state.maybeMap(orElse: () {}, getNotes: (notes) {
                      return notes.getNotes[index]['content'];
                    })}",
              );
            },
          );
        },
      ),
    );
  }
}
 

Государственным кодексом является:

 @freezed
class ScheduledNotesState with _$ScheduledNotesState {
  const factory ScheduledNotesState.initial() = _Initial;
  const factory ScheduledNotesState.getNotes({required List<Map<String, dynamic>> getNotes}) = _GetNotes;
  const factory ScheduledNotesState.getNotesCount({required int noteCount}) = _GetNotesCount;
  const factory ScheduledNotesState.getCountDoneNoteOutOfAllNotes({required String getCountDoneNoteOutOfAllNotes}) = _GetCountDoneNoteOutOfAllNotes;
  const factory ScheduledNotesState.updateIsDoneNote({required int updateIsDoneNote}) = _UpdateIsDoneNote;
}
 

Код локтя таков:

 @injectable
class ScheduledNotesCubit extends Cubit<ScheduledNotesState> {
  ScheduledNotesCubit(this._noteRepository)
      : super(const ScheduledNotesState.initial());
  final NoteRepository _noteRepository;

  // retrieve data
  void retrieveData() async {
   return emit(ScheduledNotesState.getNotes(
        getNotes: await _noteRepository.retrieveData()));
  }
}
 

Этот локоть не возвращает значение в ListView, вместо этого он возвращает нулевые значения, но когда я пытаюсь это сделать, это работает!!!!!!

обновленный код cubit является:

 @injectable
class ScheduledNotesCubit extends Cubit<ScheduledNotesState> {
  ScheduledNotesCubit(this._noteRepository)
      : super(const ScheduledNotesState.initial());
  final NoteRepository _noteRepository;

  // retrieve data
  void retrieveData() async {
    var d= await _noteRepository.retrieveData(); //-->updated
   var x= d[1]['content']; //-->updated
    print("n $x n") ; // -->updated
   return emit(ScheduledNotesState.getNotes(
        getNotes: await _noteRepository.retrieveData()));
  }
}
 

Ответ №1:

Можете ли вы попробовать добавить lazy значение false для BlocProvider и обновить этот код:

   void retrieveData() {
    _noteRepository.retrieveData().then((value) {
      emit(ScheduledNotesState.getNotes(getNotes: value));
    });
  }
 

Комментарии:

1. спасибо за ваш ответ, НО это НЕ работает! @dangngocduc

2. Можете ли вы повторить попытку с моим кодом обновления в ответе ?

3. тоже не работает! @dangngocduc

4. я ответил на свой вопрос, вы можете это видеть. спасибо, что помогли мне

Ответ №2:

Решение заключается в создании класса данных для cubit вместо создания закрытых классов.