简体   繁体   English

Flutter Bloc 中的 mapEventToState 中的当前 state 不是屈服

[英]the current state in mapEventToState in Flutter Bloc is not yield

I am trying to make a simple app for testing the BloC pattern but, there's a change in the current version of the BloC Pattern, that the "Current State" now not sending with the mapEventToState method as a parameter but according to the online document you can replace it with only "state", but it not working with me,我正在尝试制作一个简单的应用程序来测试 BloC 模式,但是,BloC 模式的当前版本发生了变化,“当前状态”现在不使用 mapEventToState 方法作为参数发送,而是根据您的在线文档只能用“状态”替换它,但它不适用于我,

and this is my code:这是我的代码:

class CounterBloc extends Bloc<CounterEvent, CounterState> {

  void onIncrement(){
     add(IncrementEvent());
  }

  void onDecrement() {
     add(DecrementEvent());
  }

  @override
  // TODO: implement initialState
  CounterState get initialState => CounterState.initial();

  @override
  Stream<CounterState> mapEventToState(CounterEvent event) async* {
    if (event is IncrementEvent) {
      yield state..counter += 1;
    } else if (event is DecrementEvent) {
      yield state..counter -= 1;
    }
  }
}

and this is the Counter state class这是计数器 state class

class CounterState {
  int counter;

  CounterState._();

  factory CounterState.initial() {
    return CounterState._()..counter = 0;
  }
}

and this is my main app dart file这是我的主要应用程序 dart 文件

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);


  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CounterBloc(),
      child: CounterWidget(widget: widget),
    );
  }
}

class CounterWidget extends StatelessWidget {

  final MyHomePage widget;

  const CounterWidget({Key key, @required this.widget}) :super (key: key);

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: BlocBuilder(
          bloc: BlocProvider.of<CounterBloc>(context),
          builder: (context, CounterState state) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'You have pushed the button this many times:',
                  ),
                  Text(
                    '${state.counter}',
                    style: Theme.of(context).textTheme.display1,
                  ),
                ],
              ),
            );
          },
        ),
        floatingActionButton: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            FloatingActionButton(
              onPressed: () => BlocProvider.of<CounterBloc>(context).onIncrement(),
              tooltip: 'Increment',
              child: Icon(Icons.add),
            ),
            SizedBox(width: 10,),
            FloatingActionButton(
              onPressed: () => BlocProvider.of<CounterBloc>(context).onDecrement(),
              tooltip: 'Decrement',
              child: Icon(Icons.remove),
            ),
          ],
        )
    );
  }
} 

please can anyone help me with this issue?请问谁能帮我解决这个问题?

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
Step 1: add CounterState({this.counter});第 1 步:添加CounterState({this.counter}); in CounterStateCounterState状态
Step 2: yield state..counter += 1;第2步: yield state..counter += 1; will not cause Widget build , please change to yield CounterState(counter: state.counter + 1);不会导致 Widget build ,请改为yield CounterState(counter: state.counter + 1);

working demo工作演示

在此处输入图像描述

full code完整代码

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

abstract class CounterEvent {}

class IncrementEvent extends CounterEvent {}

class DecrementEvent extends CounterEvent {}

void main() => runApp(MyApp());

class CounterState {
  int counter;

  CounterState._();

  CounterState({this.counter}); //add this line

  factory CounterState.initial() {
    return CounterState._()..counter = 0;
  }
}

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  void onIncrement() {
    add(IncrementEvent());
  }

  void onDecrement() {
    add(DecrementEvent());
  }

  @override
  // TODO: implement initialState
  CounterState get initialState => CounterState.initial();

  @override
  Stream<CounterState> mapEventToState(CounterEvent event) async* {
    if (event is IncrementEvent) {
      //yield state..counter += 1;
      yield CounterState(counter: state.counter + 1);
    } else if (event is DecrementEvent) {
      //yield state..counter -= 1;
      yield CounterState(counter: state.counter - 1);
    }
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CounterBloc(),
      child: CounterWidget(widget: widget),
    );
  }
}

class CounterWidget extends StatelessWidget {
  final MyHomePage widget;

  const CounterWidget({Key key, @required this.widget}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: BlocBuilder(
          bloc: BlocProvider.of<CounterBloc>(context),
          builder: (context, CounterState state) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'You have pushed the button this many times:',
                  ),
                  Text(
                    '${state.counter}',
                    style: Theme.of(context).textTheme.display1,
                  ),
                ],
              ),
            );
          },
        ),
        floatingActionButton: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            FloatingActionButton(
              onPressed: () =>
                  BlocProvider.of<CounterBloc>(context).onIncrement(),
              tooltip: 'Increment',
              child: Icon(Icons.add),
            ),
            SizedBox(
              width: 10,
            ),
            FloatingActionButton(
              onPressed: () =>
                  BlocProvider.of<CounterBloc>(context).onDecrement(),
              tooltip: 'Decrement',
              child: Icon(Icons.remove),
            ),
          ],
        ));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 URI 的目标不存在:&#39;package:flutter_bloc/flutter_bloc.dart&#39;。 安卓工作室 - Target of URI doesn't exist: 'package:flutter_bloc/flutter_bloc.dart'. Android Studio Flutter:使用不包含 Bloc 类型的上下文调用 blocprovider.of() - Flutter: blocprovider.of() called with a context that does not contain a Bloc of type OnChanged Flutter 中复选框的 State - OnChanged State of Checkbox in Flutter 使用无效回调 flutter 设置 State - Set State using Void Callback flutter 保存当前 ImageView state 用于关闭和重新打开应用程序 - Saving current ImageView state for closing and reopening a app 如何在 Flutter/Dart 中优雅地使用 state 的变量? - How do elegantly use variables for a state in Flutter/Dart? 如何使用 Flutter 从 Firebase 获取当前活跃用户? - How I can get current active users from Firebase with Flutter? Flutter 运行发布失败:支持的最低 Gradle 版本为 5.6.4。 当前版本是 5.6.2 - Flutter run release fails: Minimum supported Gradle version is 5.6.4. Current version is 5.6.2 如何在下拉菜单中仅获取月份并将默认值设置为 flutter 中的当前月份? - How to get only months in drop down and and set the default value as current month in flutter? Flutter “入口点不在当前项目中。” Android Studio 错误 - Flutter "Entrypoint isn't within the current project." error on Android Studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM