颤振没有更新肘部状态

时间:2021-03-02 12:43:52

标签: flutter dart bloc cubit

我正在练习 BloC cubit,它没有更新状态。这是我的主文件。我使用 BlocProvider 来创建实例,使用 BlocBuilder 来呈现状态,但是每当我点击增量和减量时,它都不会重新呈现文本小部件。

import 'package:bloc_counter_app/counter_cubit.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(
      title: 'bloc counter app',
      theme: ThemeData(primarySwatch: Colors.red),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bloc Counter App'),
      ),
      body: BlocProvider<CounterCubit>(
        create: (context) => CounterCubit(),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            BlocBuilder<CounterCubit, CounterState>(builder: (context, state) {
              return Text(
                state.counterValue.toString(),
                style: TextStyle(
                  fontSize: 20.0,
                ),
              );
            }),
            SizedBox(
              height: 50.0,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                FloatingActionButton(
                    tooltip: 'Increment',
                    child: Icon(Icons.add),
                    onPressed: () {
                      BlocProvider.of<CounterCubit>(context).increment();
                    }),
                FloatingActionButton(
                    tooltip: 'decrement',
                    child: Icon(Icons.remove),
                    onPressed: () =>
                        BlocProvider.of<CounterCubit>(context).decrement())
              ],
            )
          ],
        ),
      ),
    );
  }
}

这是我的柜台肘文件

import 'package:bloc/bloc.dart'; 导入 'package:meta/meta.dart';

part 'counter_state.dart';

class CounterCubit extends Cubit<CounterState> {
  CounterCubit() : super(CounterState(counterValue: 0));

  void increment() => emit(CounterState(counterValue: state.counterValue + 1));

  void decrement() => emit(CounterState(counterValue: state.counterValue - 1));
}

这是我的计数器状态文件

part of 'counter_cubit.dart';



class CounterState {
  int counterValue;

  CounterState({@required this.counterValue});
}

1 个答案:

答案 0 :(得分:1)

在按钮的回调中,您试图通过提供它的相同上下文来获取肘。创建一个单独的小部件或用 Builder 包裹子部件。更多信息here