简体   繁体   English

您如何在 Dart (Bloc/Flutter) 中以有效的方式执行此列表操作?

[英]How do you do this list operations in an efficient way in Dart (Bloc/Flutter)?

I have BLoC with the following state which contains 2 words ,我的 BLoC 具有以下状态,其中包含 2 个单词,

// 2 words are fixed and same length.
// in word_state.dart
abstract class WordState extends Equatable 
  const WordState(this.quest, this.answer, this.word, this.clicked);
  final List<String> wordA; // WordA = ['B','A','L',L']
  final List<String> wordB; // WordB = ['','','','']
  @override
  List<Object> get props => [wordA,wordB];
}

I want to ADD and REMOVE letters.我想添加和删除字母。

// in word_event.dart
class AddLetter extends WordEvent {
  final int index;
  const AddLetter(this.index);
}
class RemoveLetter extends WordEvent {
  final int index;
  const RemoveLetter(this.index);
}

1.ADD: If I select the index of 'L' in wordA, then I add the letter 'L' in the first occurrence of '' (empty) in wordB. 1.添加:如果我在wordA中选择'L'的索引,那么我在wordB中第一次出现''(空)时添加字母'L'。

// in word_bloc.dart 
void _onLetterAdded(AddLetter event, Emitter<WordState> emit) {
  final b = [...state.wordB]; 
  b[b.indexOf('')] = state.wordA[event.index];
  emit(WordLoaded(state.wordA, b));
}
//wordB, ['','','',''] into ['L','','','']

2.REMOVE: If I deselect the index of 'L' in wordA, then I remove the last occurence of letter 'L' in wordB and shift the right side letters to left 2.REMOVE:如果我取消选择wordA中'L'的索引,那么我删除wordB中最后出现的字母'L'并将右侧字母向左移动

 void _onLetterRemoved(RemoveLetter event, Emitter<WordState> emit) {
    final b = [...state.wordB];
    final index = b.lastIndexOf(state.wordA[event.index]);
    for (int i = index; i < 4 - 1; i++) { 
      b[i] = b[i + 1];
    }
    b[3] = '';
    emit(WordLoaded(state.wordA, b));
  }
}
// What i am trying to
// ['B','L','A','L']
// if index is 1 then ['B','A','L','']

This code is working fine, But I want to do the list operations in efficient way.这段代码工作正常,但我想以有效的方式进行列表操作。

can you please check this code understand it and run it on dart pad.你能检查一下这段代码是否理解它并在飞镖垫上运行它。

  List<String> wordA=['B','A','L','L'];
  List<String> wordB=['','','',''];

  List<String> wordBAll=['B','L','A','L'];
  void main() {
  wordB.insert(0,wordA[2]);
  wordBAll.removeAt(wordBAll.length-1);
  print(wordB);
  print(wordBAll);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM