【问题标题】:The bloc state does not work when entering the application - Flutter进入应用时bloc状态不起作用-Flutter
【发布时间】:2022-01-17 16:26:08
【问题描述】:

当我进入应用程序时,应该执行状态检查(todo_list)。如果没有列表,那么它应该写No Todo,如果有,那么它应该加载。在我的情况下,如果数据库中没有数据,那么只是一个没有文本的黑屏。因此,事实证明检查没有发生,或者可能是什么原因?我将不胜感激:)

todo_bloc

  class TodoBloc extends Bloc<TodoEvent, TodoState> {
  final TodoRepository todoRepository;

  TodoBloc(this.todoRepository) : super(TodoEmptyState()) {
    on<LoadTodos>((event, emit) async {
      emit(TodoLoadingState());
      try {
        final List<Todo> _loadedTodoList = await todoRepository.getAllTodos();
        emit(TodoLoadedState(loadedUser: _loadedTodoList));
      } catch (_) {
        emit(TodoErrorState());
      }
    });

todo_state

abstract class TodoState extends Equatable {
  const TodoState();

  @override
  List<Object> get props => [];
}

class TodoEmptyState extends TodoState {}

待办事项列表

    class TodoList extends StatefulWidget {
  @override
  State<TodoList> createState() => _TodoListState();
}

class _TodoListState extends State<TodoList> {
  @override
  void initState() {
    super.initState();
    BlocProvider.of<TodoBloc>(context).add(LoadTodos());
  }

  @override
  void dispose() {
    BlocProvider.of<TodoBloc>(context).close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final TodoBloc todoBloc = context.read<TodoBloc>();
    return BlocBuilder<TodoBloc, TodoState>(builder: (context, state) {
      if (state is TodoEmptyState) {
        return const Center(
          child: Text(
            'No Todo',
            style: TextStyle(fontSize: 20.0, color: Colors.white),
          ),
        );
      }

      if (state is TodoLoadingState) {
        return const Center(child: CircularProgressIndicator());
      }

      if (state is TodoLoadedState) {
        return ListView.builder(
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemCount: state.loadedUser.length,
            itemBuilder: (context, index) => Card(
                  shadowColor: Colors.blueGrey,
                  margin: const EdgeInsets.only(left: 15, right: 15, top: 8),
                  color: Colors.black,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.grey.shade800, width: 0.5),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  borderOnForeground: false,
                  child: ListTile(
                    title: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${state.loadedUser[index].description}',
                            style: const TextStyle(
                              fontSize: 21.0,
                              // fontWeight: FontWeight.bold,
                            ),
                          ),
                          // Text('${state.loadedUser[index].id}'),
                        ]),
                    trailing: IconButton(
                      tooltip: 'Delete Todo',
                      highlightColor: Colors.red,
                      onPressed: () {
                        todoBloc
                            .add(DeleteTodos(id: state.loadedUser[index].id));
                      },
                      icon: const Icon(
                        Icons.delete,
                        color: Colors.white,
                      ),
                    ),
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => EditTodoScreen(
                            todo: state.loadedUser[index],
                          ),
                        ),
                      );
                    },
                  ),
                ));
      }
      return const SizedBox.shrink();
    });
  }
}

索引 0 处的 1 个元素被转移到调试中进入 TodoLoadedState 状态,虽然我没有创建它,也许正因为如此 TodoEmptyState 状态不起作用?

【问题讨论】:

  • 您要添加活动吗?你能展示你完整的TodoBloc构造函数和build方法吗?
  • 好的,完全添加了构建方法和todo_bloc
  • 在获取待办事项时是否可能出错?你能在你的TodoBloc 上添加print(_) 吗?

标签: flutter dart flutter-layout flutter-dependencies flutter-web


【解决方案1】:

尝试添加参数listen: false,同时在您的 initState 中访问提供程序:

BlocProvider.of<TodoBloc>(context,listen:false).add(LoadTodos());

这是因为如果你想在你的 initState 中访问 provider,你应该将 listen 参数设置为 false。

【讨论】:

  • 我试过了,可惜没用,还是没有显示“No Todo”
  • 控制台有错误吗?
  • 您问题中的 todo_list 不包含完整代码,请更新。也不推荐在 build 函数中使用 context.read!
  • 没有错误,当它进入应用程序时 - 它没有写任何东西。添加所有代码 todo_list
  • 以及用什么代替 context.read?
猜你喜欢
  • 2020-01-14
  • 2021-03-19
  • 2020-05-06
  • 2021-12-23
  • 2020-08-03
  • 2021-08-02
  • 2020-07-09
  • 2021-03-04
  • 2020-04-12
相关资源
最近更新 更多