我正在练习 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});
}