3

我对 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 => [];
}

我在 main.dart 文件中用 BlocProvider 包装了我的 HomePage,以在 HomePage 中访问我的 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()))),
    );
  }
}

试图将我的 HomePage 类设为 StateLessWidget,但问题仍然存在,现在我的类是 StateFulWidget,也有同样的问题。我在 initState 方法中得到 AllUsers

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),
    ));
  }
}

我的目标是告诉用户列表为空并在出现 UserLoadingError 状态时显示一个小吃栏,但我只看到一个卡住的 LoadingIndicator 我的“打印”调试器在日志中显示:
I/flutter (14034): bloc builder
I/flutter (14034 ): getallusers
I/flutter (14034): bloc builder
I/flutter (14034): 出错了 (userBloc)
I/flutter (14034): 显示snackbar (listener)

预期结果:
I/flutter (14034): bloc builder
I/flutter (14034): getallusers
I/flutter (14034): bloc builder
I/flutter (14034): got an error (userBloc)
I/flutter (14034): 显示snapbar (listener) /// 在这条消息之后应该出现一个snackbar
I/flutter (14034): bloc builder
I/flutter (14034): state is empty/error (builder) /// 在这之后应该创建一个空列表布局信息

pubspecs.yaml 片段:
依赖项:
flutter:
sdk:flutter
cupertino_icons:^0.1.3
chopper:^3.0.2
equatable:^1.1.1
flutter_bloc:^4.0.0
provider:^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:flutter

我可以上传我的 UserService 类,在那里我使用 Chopper 从 API 获取用户,如果需要,请告诉我。

4

1 回答 1

1

最后我发现了一个问题。问题出在我的 BlockBuilder if/else 树中,更准确地说:

if (state is UserLoading || state is UserInitial)
                return _showLoadingStatus();

我变成了:

if (state is UserLoading)
                return _showLoadingStatus();

现在问题消失了。

于 2020-05-19T12:06:34.387 回答