我有一个桌面视图,我有流行的,最近的和即将到来的类别。它们在api上都有相同的响应。我正在尝试使用flutter_bloc从api中获取数据。以前,我使用的是rxdart主题,我为每种类型的数据创建了一个主题。现在,使用颤振集团,我想实现同样的目标。我想要做的是在选项卡之间切换。在此之前,我使用行为主体将数据保存到下一个事件,但现在我希望过渡到集团模式。如何使用flutter_bloc实现相同类型的结果?还是我需要为每种类型创建一个区块?最后,如何从api中获取数据,以便在切换制表符时保持状态?我的Rxdart实现:
class DataBloc {
final DataRepo _repository = DataRepo();
final BehaviorSubject<Data> _recent = BehaviorSubject<Data>();
final BehaviorSubject<Data> _popular = BehaviorSubject<Data>();
final BehaviorSubject<Data> _upcoming = BehaviorSubject<Data>();
getData(String type) async {
Data response = await _repository.getData(type);
if (type == "recent") {
_recent.sink.add(response);
} else if (type == "upcoming") {
_upcoming.sink.add(response);
} else {
_popular.sink.add(response);
}
}
dispose() {
_recent?.close();
_popular?.close();
_upcoming?.close();
}
BehaviorSubject<Data> get recent => _recent;
BehaviorSubject<Data> get popular => _popular;
BehaviorSubject<Data> get upcoming => _upcoming;
}发布于 2020-11-10 14:57:52
毫无疑问,你的问题没有一个单一的解决方案。我将回答您的问题,我将给您一个完整的实现/示例,以便于理解。
我需要为每种类型创建一个区块?
我建议您为每个数据创建一个BLoC (例如),因为它将简化BLoC的逻辑(特别是如果您不想一次加载所有数据),并且应用程序将是结构化的,耦合性较小,这是很好的。但是,如果您愿意,仍然可以在一个BLoC中完成这一任务。
如何从api中获取数据,以便在切换选项卡时保持状态?
是,一旦使用相同的BLoC/Cubit实例,状态就会保持不变。每次你建立集团(使用BlocBuilder),你将得到最后的状态。在我的示例中,当选项卡视图呈现时,我们只调用一次load()事件。
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
///
/// The repository that is shared among all BLOCs
///
final Repository repository = Repository();
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
// For example purpose I will expose them as global cubits
return MultiBlocProvider(
providers: [
BlocProvider<PopularCategoriesCubit>(
create: (context) =>
// Create the cubit and also call the LOAD event right away.
//
// NOTE #4. The cubit is created only when is requested (by
// BlocBuilder, BlocListener, etc). This is why when you move to
// a FRESH NEW tab you see the loading state.
//
PopularCategoriesCubit(repository: repository)..load(),
),
BlocProvider<RecentCategoriesCubit>(
create: (context) =>
RecentCategoriesCubit(repository: repository)..load(),
),
BlocProvider<UpcomingCategoriesCubit>(
create: (context) =>
UpcomingCategoriesCubit(repository: repository)..load(),
),
],
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
));
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text("Bloc Tabs"),
bottom: TabBar(
tabs: [
Tab(text: "Popular"),
Tab(text: "Recent"),
Tab(text: "Upcoming"),
],
),
),
body: TabBarView(
children: [
// POPULAR TAB
BlocBuilder<PopularCategoriesCubit, GenericState>(
builder: (context, state) {
if (state.isFailed)
return Text("Failed to fetch popular categories.");
if (state.isLoading)
return Text("Loading popular categories...");
return ListView(
children: [
for (var category in state.categories) Text(category)
],
);
},
),
// RECENT TAB
BlocBuilder<RecentCategoriesCubit, GenericState>(
builder: (context, state) {
if (state.isFailed)
return Text("Failed to fetch recent categories.");
if (state.isLoading)
return Text("Loading recent categories...");
return ListView(
children: [
for (var category in state.categories) Text(category)
],
);
},
),
// UPCOMMING TAB
BlocBuilder<UpcomingCategoriesCubit, GenericState>(
builder: (context, state) {
if (state.isFailed)
return Text("Failed to fetch upcoming categories.");
if (state.isLoading)
return Text("Loading upcoming categories...");
return ListView(
children: [
for (var category in state.categories) Text(category)
],
);
},
),
],
),
// This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}
// =============================================================================
///
/// Repository Mock
///
class Repository {
///
/// Retreive data by type.
///
/// NOTE #1. Is better to use enum instead of String.
///
Future<List<String>> getData(String type) async {
// Emulate netword delay
return Future<List<String>>.delayed(Duration(seconds: 2)).then((_) {
switch (type) {
case "popular":
return [
"Popular 1",
"Popular 2",
"Popular 3",
"Popular 5",
"Popular 6"
];
case "recent":
return [
"Recent 1",
"Recent 2",
"Recent 3",
];
case "upcoming":
default:
return [
"Upcomming 1",
"Upcomming 2",
];
}
});
}
}
///
/// This is a generic state used for all categories types
///
/// NOTE #2. Use Equatable. Also if you feel you can break this GenericState in
/// multiple classes as CategoriesLoadedState, CategoriesLoadingState,
/// CategoriesFailedState ...
///
class GenericState {
///
/// Categories data
///
final List<String> categories;
///
/// Tells the data is loading or not
///
final bool isLoading;
///
/// Tells whether the state has errors or not
///
final bool isFailed;
GenericState(
{this.categories, this.isLoading = false, this.isFailed = false});
}
///
/// Popular categories Cubit
///
class PopularCategoriesCubit extends Cubit<GenericState> {
///
/// Repository dependency
///
final Repository repository;
///
/// Cubit constructor. Send a loading state as default.
///
PopularCategoriesCubit({@required this.repository})
: super(GenericState(isLoading: true));
// ==================================
// EVENTS
// ==================================
///
/// Load data from repository
///
void load() async {
//#log
print("[EVENT] Popular Categories :: Load");
// Every time when try to load data from repository put the application
// in a loading state
emit(GenericState(isLoading: true));
try {
// Wait for data from repository
List categories = await this.repository.getData("popular");
// Send a success state
emit(GenericState(categories: categories, isFailed: false));
} catch (e) {
// For debugging
print(e);
// For example purpose we do not have a message
emit(GenericState(isFailed: true));
}
}
}
///
/// Recent categories Cubit
///
class RecentCategoriesCubit extends Cubit<GenericState> {
///
/// Repository dependency
///
final Repository repository;
///
/// Cubit constructor. Send a loading state as default.
///
RecentCategoriesCubit({@required this.repository})
: super(GenericState(isLoading: true));
// ==================================
// EVENTS
// ==================================
///
/// Load data from repository
///
void load() async {
//#log
print("[EVENT] Recent Categories :: Load");
// Every time when try to load data from repository put the application
// in a loading state
emit(GenericState(isLoading: true));
try {
// Wait for data from repository
List categories = await this.repository.getData("recent");
// Send a success state
emit(GenericState(categories: categories, isFailed: false));
} catch (e) {
// For debugging
print(e);
// For example purpose we do not have a message
emit(GenericState(isFailed: true));
}
}
}
///
/// Upcoming categories Cubit
///
class UpcomingCategoriesCubit extends Cubit<GenericState> {
///
/// Repository dependency
///
final Repository repository;
///
/// Cubit constructor. Send a loading state as default.
///
UpcomingCategoriesCubit({@required this.repository})
: super(GenericState(isLoading: true));
// ==================================
// EVENTS
// ==================================
///
/// Load data from repository
///
void load() async {
//#log
print("[EVENT] Upcoming Categories :: Load");
// Every time when try to load data from repository put the application
// in a loading state
emit(GenericState(isLoading: true));
try {
// Wait for data from repository
List categories = await this.repository.getData("upcoming");
// Send a success state
emit(GenericState(categories: categories, isFailed: false));
} catch (e) {
// For debugging
print(e);
// For example purpose we do not have a message
emit(GenericState(isFailed: true));
}
}
}只需将代码复制并粘贴到main.dart中,就可以看到结果。我试图尽可能多地对代码进行注释,以帮助您理解。
此外,我推荐从零到英雄的集团教程。它将极大地帮助您理解和正确使用BLoC库。
更新1
每次更改Tab时重新加载数据
若要在每次更改Tab时重新加载数据,您可以从onTap中使用TabBar,如下所示。
TabBar(
onTap: (tabIndex) {
switch (tabIndex) {
// Popular
case 0:
BlocProvider.of<PopularCategoriesCubit>(context).load();
break;
// Recent
case 1:
BlocProvider.of<RecentCategoriesCubit>(context).load();
break;
// Upcoming
case 2:
BlocProvider.of<UpcomingCategoriesCubit>(context).load();
break;
}
},
tabs: [
Tab(text: "Popular"),
Tab(text: "Recent"),
Tab(text: "Upcoming"),
],
),注意:现在您不必在创建最近的和即将到来的丘比特时发出(非默认选项卡)--因为Tab tap会处理这个问题。
BlocProvider<RecentCategoriesCubit>(
create: (context) =>
RecentCategoriesCubit(repository: repository),
),
BlocProvider<UpcomingCategoriesCubit>(
create: (context) =>
UpcomingCategoriesCubit(repository: repository),
),https://stackoverflow.com/questions/64629233
复制相似问题