集团不更新状态。谁能告诉我这段代码有啥问题。这是我第一次尝试使用 bloc 架构

Posted

技术标签:

【中文标题】集团不更新状态。谁能告诉我这段代码有啥问题。这是我第一次尝试使用 bloc 架构【英文标题】:Bloc not updating state. Can anybody tell me what is wrong with this code. This is my first try with bloc architecture集团不更新状态。谁能告诉我这段代码有什么问题。这是我第一次尝试使用 bloc 架构 【发布时间】:2021-09-12 06:05:52 【问题描述】:

集团没有更新状态。谁能告诉我这段代码有什么问题。有两个按钮,第一个触发第一个事件,第二个按钮触发第二个事件。但就我而言,状态没有更新。我不知道为什么这不是在我的情况下更新状态。

集团类

  class MyBloc extends Bloc<MyEvent, MyState> 
  MyBloc() : super(LoadingState());

  @override`enter code here`
  Stream<MyState> mapEventToState(MyEvent event) async* 
    if (event is FirstEvent) 
      yield* firstFunction();
     else if (event is SecondEvent) 
      yield* secondFunction();
    
  

  Stream<MyState> firstFunction() async* 
    yield LoadingState();
    try 
      final String name = Repository().getFirstName();
      yield FirstState(name: name);
     on Exception 
      yield ErrorState();
     catch (_) 
      yield ErrorState();
    
  

  Stream<MyState> secondFunction() async* 
    yield LoadingState();
    try 
      final String name = Repository().getLastName();
      yield SecondState(name: name);
     on Exception 
      yield ErrorState();
     catch (_) 
      yield ErrorState();
    
  

事件类

@immutable
abstract class MyEvent extends Equatable 
  const MyEvent();


class FirstEvent extends MyEvent 
  const FirstEvent();

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


class SecondEvent extends MyEvent 
  const SecondEvent();

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

状态类

@immutable
abstract class MyState extends Equatable 
  const MyState();


class LoadingState extends MyState 
  const LoadingState();

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


class FirstState extends MyState 
  const FirstState(required this.name);
  final String name;

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


class SecondState extends MyState 
  const SecondState(required this.name);
  final String name;

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


class ErrorState extends MyState 
  const ErrorState();

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

存储库

class Repository 
  /// get data from api
  String getFirstName() 
    return "First name";
  

  String getLastName() 
    return "last name";
  

主屏幕

class MyHomePage extends StatefulWidget 
  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  MyBloc _myBloc = MyBloc();
  @override
  void dispose() 
    _myBloc.close();
    super.dispose();
  
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
          child: Column(
        children: [
          SizedBox(
            height: 150,
          ),
          BlocBuilder<MyBloc, MyState>(builder: (context, state) 
            if (state is LoadingState) 
              return CircularProgressIndicator();
             else if (state is FirstState) 
              return Text(state.name);
             else if (state is SecondState) 
              return Text(state.name);
             else if (state is ErrorState) 
              return Text("Error");
            
            return const SliverFillRemaining(
              child: Text('Something went wrong!'),
            );
          ),
          SizedBox(
            height: 50,
          ),
          GestureDetector(
            onTap: () async
              _myBloc.add(FirstEvent());
              await Future.delayed(Duration.zero);
            ,
            child: Container(
              color: Colors.greenAccent,
              width: 200,
              height: 50,
              child: Center(
                child: Text("Show First Name"),
              ),
            ),
          ),
          SizedBox(
            height: 50,
          ),
          GestureDetector(
            onTap: () async
              _myBloc.add(SecondEvent());
              await Future.delayed(Duration.zero);
            ,
            child: Container(
              color: Colors.greenAccent,
              width: 200,
              height: 50,
              child: Center(
                child: Text("Show Last Name"),
              ),
            ),
          )
        ],
      )),
    );
  

主要功能

void main() 
  runApp(MyApp());

我的应用

class MyApp extends StatelessWidget 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return BlocProvider(
      create: (context) => MyBloc(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(**strong text**
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(),
      ),
    );
  

【问题讨论】:

【参考方案1】:

您的问题是如何初始化 MyBloc 实例。

查看the docs 了解更多信息,但基本上不是这个

MyBloc _myBloc = MyBloc();

在您的构建方法中像这样初始化您的MyBloc,以便它可以访问上下文。

final _myBloc = context.read<MyBloc>();

这应该会更新您的状态。

【讨论】:

以上是关于集团不更新状态。谁能告诉我这段代码有啥问题。这是我第一次尝试使用 bloc 架构的主要内容,如果未能解决你的问题,请参考以下文章

这个 NSFetchRequest 有啥问题?

你能告诉我这段代码在做啥吗?

我尝试了多种方法,谁能告诉我这个数组有啥问题?

这段代码有啥错误

Days 和 TotalDays 之间有啥区别? [关闭]

看看这段代码,如果有啥我可以改变的,请告诉我