我正在尝试找出定义搜索集团状态以在所有状态类中保留text
属性(搜索关键字)的最佳方法。
当前,它看起来像这样:
import 'package:equatable/equatable.dart';
import 'package:project/models/searchResults.dart';
class SearchState extends Equatable {
SearchState([List props = const []]) : super(props);
}
class SearchStateEmpty extends SearchState {
final String text;
SearchStateEmpty({this.text});
@override
String toString() => 'SearchStateEmpty';
}
class SearchStateLoading extends SearchState {
final String text;
SearchStateLoading({this.text});
@override
String toString() => 'SearchStateLoading';
}
class SearchStateSuccess extends SearchState {
final String text;
final List<RestaurantSearchItem> items;
SearchStateSuccess({this.text, this.items}) : super([text, items]);
@override
String toString() => 'SearchStateSuccess { items: ${items.length} }';
}
class SearchStateError extends SearchState {
final String text;
final String error;
SearchStateError({this.text, this.error}) : super([text, error]);
@override
String toString() => 'SearchStateError';
}
是否有比在所有状态类中定义text
属性更好的方法?
如果我不必每次没有事件时都使用currentState
属性,这将不会像现在这样糟糕。例如:
SearchStateEmpty(text: currentState.text);
...
SearchStateLoading(text: event.text);
...
SearchStateSuccess(text: currentState.text, items: results.items);
我一直在寻找Flutter文档中的示例,但我能发现的是我应该为此使用不同的块,或者使用沟equatable
(我希望保留它,因为它非常不错)。
任何带有示例的建议将不胜感激。谢谢。
答案 0 :(得分:0)
我这样做的方式是一种反模式。在一些帮助下,我能够找到一种更干净的方式来使用状态类中的当前状态。
代码现在看起来像这样:
class SearchState extends Equatable {
final String text;
SearchState(this.text,
[List<RestaurantSearchItem> items = const [], String error = ''])
: super([text, items, error]);
}
class SearchStateEmpty extends SearchState {
SearchStateEmpty({String text})
: super(text); // Here I want to use text from SearchState
SearchStateEmpty.fromState(SearchState state) : super(state.text);
@override
String toString() => 'SearchStateEmpty';
}
class SearchStateLoading extends SearchState {
final String text;
SearchStateLoading({this.text})
: super(text); // Here I want to set text that comes from event
@override
String toString() => 'SearchStateLoading';
}
class SearchStateError extends SearchState {
final String error;
SearchStateError({this.error, String text}) : super(text, [], error);
// Text comes from SearchState, error comes from event
SearchStateError.fromState(SearchState state, {this.error})
: super(state.text, [], error);
@override
String toString() => 'SearchStateError';
}
class SearchStateSuccess extends SearchState {
final List<RestaurantSearchItem> items;
SearchStateSuccess({this.items, String text}) : super(text, items, null);
SearchStateSuccess.fromState(SearchState state, {this.items})
: super(state.text, items, null);
@override
String toString() => 'SearchStateSuccess { items: ${items.length} }';
}