1

我目前正在尝试学习颤振的状态管理,并且我有以下代码,但由于某种原因,状态从未更新,我错过了什么吗?

import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BlocProvider(
        create: (context) => ItemBloc(),
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Bloc Demo"),
      ),
      body: Lister(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ItemBloc().add(AddEvent());
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Lister extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ItemBloc, ListState>(
      builder: (context, state) {
        if (state is ListAdded) {
          return ListView.builder(
            itemCount: state.items.length,
            itemBuilder: (context, index) {
              return Text("item"); // This never increases in count
            },
          );
        }
        return Center(
          child: Text('err'),
        );
      },
    );
  }
}

// BLOC
class ItemBloc extends Bloc<ListEvent, ListState> {
  @override
  get initialState => ListAdded(items: ["initial"]);

  @override
  Stream<ListState> mapEventToState(ListEvent event) async* {
    if (event is AddEvent) {
      final lister = ["first", "second"];
      yield ListAdded(items: lister);
    }
  }
}

abstract class ListEvent extends Equatable {
  @override
  List<Object> get props => [];
}

class AddEvent extends ListEvent {}

abstract class ListState extends Equatable {
  const ListState();

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

class ListAdded extends ListState {
  final List<String> items;

  const ListAdded({
    this.items,
  });

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

  @override
  String toString() => 'ItemsLoaded { items: ${items.length} }';
}

请注意:我尝试将代码分离到单独的文件中,并在 Bloc 文件中导入bloc.dart包而不是包flutter_bloc.dart

4

1 回答 1

3

当你这样做

ItemBloc().add(AddEvent())

您正在创建新的 bloc 实例并向其添加事件。它与在 中创建MyApp和使用的没有连接Lister

你应该得到创建的块:

BlocProvider.of<ItemBloc>(context).add(AddEvent())
于 2020-05-28T20:06:14.283 回答