我对 Flutter Bloc 包有问题。主要思想是从 API 获取用户列表,我打开互联网以查看我的错误状态如何工作,但是当 try/catch 块捕获错误时,我的 Bloc Builder 没有重建,我的 UI 也没有改变,我必须进行热重启才能看到结果。
用户组类:
import 'dart:io';
import 'package:chopper/chopper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:listviewblocflutter/bloc/user/user_event.dart';
import 'package:listviewblocflutter/bloc/user/user_state.dart';
import 'package:listviewblocflutter/data/error/network_error.dart';
import 'package:listviewblocflutter/data/service/user_service.dart';
import 'package:listviewblocflutter/model/built/built_user.dart';
import 'package:built_collection/built_collection.dart';
class UserBloc extends Bloc<UserEvent, UserState> {
UserService _userService;
UserBloc() {
this._userService = UserService.create();
}
@override
UserState get initialState => UserInitial();
@override
Stream<UserState> mapEventToState(UserEvent event) async* {
yield UserLoading();
if (event is GetAllUsers) {
print("getallusers");
try {
final listOfUsers = await _userService.getAllUsers();
yield UsersLoaded(listOfUsers.body);
print("users loaded (userBloc)");
} catch (_) {
print("got an error (userBloc)");
yield UserLoadingError("Can't get all users!");
}
} else if (event is GetUserById) {
// single user event
}
}
}
用户事件类:
import 'package:equatable/equatable.dart';
abstract class UserEvent extends Equatable {
const UserEvent();
}
class GetAllUsers extends UserEvent {
const GetAllUsers();
@override
List<Object> get props => [];
}
class GetUserById extends UserEvent {
final int id;
const GetUserById(this.id);
@override
List<Object> get props => [id];
}
用户状态类:
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:listviewblocflutter/model/built/built_user.dart';
import 'package:built_collection/built_collection.dart';
@immutable
abstract class UserState extends Equatable {
const UserState();
}
class UserInitial extends UserState {
const UserInitial();
@override
List<Object> get props => [];
}
class UserLoading extends UserState {
const UserLoading();
@override
List<Object> get props => [];
}
class UserLoaded extends UserState {
final BuiltUser user;
const UserLoaded(this.user);
@override
List<Object> get props => [user];
}
class UsersLoaded extends UserState {
final BuiltList<BuiltUser> listOfUsers;
const UsersLoaded(this.listOfUsers);
@override
List<Object> get props => [listOfUsers];
}
class UserLoadingError extends UserState {
final String message;
const UserLoadingError(this.message);
@override
List<Object> get props => [message];
}
class UserEmpty extends UserState {
const UserEmpty();
@override
List<Object> get props => [];
}
我用 BlocProvider 将我的主页包装在 main.dart 文件中,以便在主页中访问我的 UserBloc:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'ListView with BLoC pattern',
home: SafeArea(
child: Scaffold(
body: BlocProvider(
create: (context) => UserBloc(), child: HomePage()))),
);
}
}
试图将我的主页类设置为StateLessWidget,但问题仍然存在,现在我的类是StateFulWidget,具有相同的问题。我在初始化状态方法中获取所有用户:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:listviewblocflutter/bloc/bloc.dart';
import 'package:listviewblocflutter/model/built/built_user.dart';
import 'package:built_collection/built_collection.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
BlocProvider.of<UserBloc>(context).add(GetAllUsers());
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Users"),
),
body: Container(
child: BlocListener<UserBloc, UserState>(
listener: (context, state) {
if (state is UserLoadingError) {
print("showing snackbar (listener)");
_showNetworkErrorSnackbar(context, state.message);
}
},
child: BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
print("bloc builder");
if (state is UserLoading || state is UserInitial)
return _showLoadingStatus();
else if (state is UsersLoaded)
return _buildList(state.listOfUsers);
else if (state is UserEmpty || state is UserLoadingError) {
print("state is empty/error (builder)");
return _emptyListLayout();
}
return Center();
},
),
),
),
);
}
ListView _buildList(BuiltList<BuiltUser> listOfUsers) {
return ListView.builder(
itemCount: listOfUsers.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.redAccent,
),
title: Padding(
padding: EdgeInsets.only(left: 10),
child: Text(
listOfUsers[index].username,
overflow: TextOverflow.ellipsis,
),
),
),
);
});
}
Widget _showLoadingStatus() {
return Center(
child: CircularProgressIndicator(),
);
}
Widget _emptyListLayout() {
return Center(
child: Text(
"List is empty ;(",
textAlign: TextAlign.center,
),
);
}
void _showNetworkErrorSnackbar(BuildContext context, String message) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(message),
));
}
}
我的目标是告诉用户列表是空的,并在出现UserLoadError状态时显示一个小吃栏,但我只看到一个卡住的加载指示器 我在日志中的"打印"调试器说:
I/颤振 (14034(:块生成器 I/颤振 (14034(:获取所有用户
I/颤振 (14034(:块生成器
I/颤振 (14034(:出现错误(用户Bloc(I/颤振 (14034(:显示小吃栏(侦听器(
预期结果:I/颤振 (14034(: 集团生成器 I/颤振 (14034(: 获取所有用户 I/颤振 (14034(: 集团生成器 I/颤振 (14034(: 出现错误 (用户集团(I/颤振 (14034(:显示 snackbar (侦听器(///此消息后应出现一个小吃栏 I/颤振 (14034(: 集团生成器 I/颤振 (14034(: 状态为空/错误 (生成器
(
///应在此消息
之后创建一个空列表布局
Pubspecs.yaml 片段:依赖:颤振:SDK:
颤振
cupertino_icons: ^0.1.3
斩波器: ^3.0.2
等式: ^1.1.1 flutter_bloc: ^4.0.0 提供程序: ^4.1.1 built_value:
^7.1.0
dev_dependencies:
chopper_generator: ^3.0.4
build_runner: ^1.10.0 built_value_generator: ^7.1.0
flutter_test:SDK:
颤振
我可以上传我的用户服务类,在那里我使用 Chopper 从 API 获取用户,如果需要,请告诉我。
最后我发现了一个问题。问题出在我的块生成器if/else树中,更准确地说:
if (state is UserLoading || state is UserInitial)
return _showLoadingStatus();
我改成:
if (state is UserLoading)
return _showLoadingStatus();
现在问题消失了。