Flutter Bloc Builder не вызывается и не обновляет пользовательский интерфейс после изменения состояния

У меня проблема с пакетом Flutter Bloc. Основная идея - получить список пользователей из API, я отключился от Интернета, чтобы посмотреть, как работает мое состояние ошибки, но когда блок try / catch вылавливает ошибку, мой Bloc Builder не восстанавливается, и мой пользовательский интерфейс не меняется, а у меня выполнить горячий перезапуск, чтобы увидеть результаты.

UserBloc класс:

    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
    }
  }
}

UserEvent класс:

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];
}

UserState класс:

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 в HomePage:

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 с той же проблемой. Я получаю AllUsers в методе initState:

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

My goal is to tell the user that list is empty and show a snackbar when UserLoadingError state appears, but I only see a stuck LoadingIndicator My "print" debugger in logs says:
I/flutter (14034): bloc builder
I/flutter (14034): getallusers
I/flutter (14034): bloc builder
I/flutter (14034): got an error (userBloc)
I/flutter (14034): showing snackbar (listener)

Expected results:
I/flutter (14034): bloc builder
I/flutter (14034): getallusers
I/flutter (14034): bloc builder
I/flutter (14034): got an error (userBloc)
I/flutter (14034): showing snackbar (listener) /// a snackbar should appear after this message
I/flutter (14034): bloc builder
I/flutter (14034): state is empty/error (builder) /// an empty list layout should be created after this message

pubspecs.yaml fragment:
dependencies:
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

I could upload my UserService class where I get users from API using Chopper, let me know if it's needed.

1 ответ

Наконец-то я обнаружил проблему. Проблема была в моем дереве BlockBuilder if/else, точнее:

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

я изменился на:

if (state is UserLoading)
                return _showLoadingStatus();

И вот проблема исчезла.

Другие вопросы по тегам