赞
踩
前言
在Flutter中,BLoC(Business Logic Component)是一种用于处理业务逻辑和状态管理的设计模式。BLoC模式将应用程序分为三个主要部分:事件(Event)、状态(State)和逻辑(Logic)。让我们看一下如何在Flutter中使用BLoC进行状态管理,并提供一个简单的例子。
首先,在pubspec.yaml文件中添加和依赖:bloc、flutter_bloc、equatable
flutter_bloc: ^8.1.3
bloc: ^8.1.2
equatable: ^2.0.5
运行flutter pub get获取依赖。
创建一个包含所有可能事件的事件类。事件是触发状态变化的动作。
import 'package:equatable/equatable.dart';
//创建事件类
abstract class CounterEvent extends Equatable{
@override
List<Object?> get props => [];
}
class IncrementEvent extends CounterEvent {}
class DecrementEvent extends CounterEvent {}
创建状态类以表示应用程序中的不同状态。状态是由事件触发并影响用户界面的数据。
import 'package:equatable/equatable.dart';
//创建状态类
abstract class CounterState extends Equatable{
final int count;
CounterState(this.count);
@override
List<Object?> get props => [count];
}
class InitialCounterState extends CounterState{
InitialCounterState(int count) : super(count);
}
class UpdatedCounterState extends CounterState{
UpdatedCounterState(int count) : super(count);
}
创建一个继承自类的BLoC类,将事件映射到状态变化的逻辑写在这里。
import 'package:bloc/bloc.dart';
import 'package:untitled1/counter_event.dart';
import 'package:untitled1/counter_state.dart';
class CounterBloc extends Bloc<CounterEvent,CounterState>{
CounterBloc() : super(InitialCounterState(0)) {
// Register handlers for IncrementEvent and DecrementEvent
on<IncrementEvent>((event, emit) {
emit(UpdatedCounterState(state.count + 1));
});
on<DecrementEvent>((event, emit) {
emit(UpdatedCounterState(state.count - 1));
});
}
@override
Stream<CounterState> mapEventToState(CounterEvent event) async*{
}
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:untitled1/CounterBloc.dart';
import 'package:untitled1/counter_event.dart';
import 'package:untitled1/counter_state.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: BlocProvider(
create: (context) => CounterBloc(),
child: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
}
@override
void dispose() async {
context.read<CounterBloc>().close();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.resumed:
break;
case AppLifecycleState.inactive:
case AppLifecycleState.paused:
break;
case AppLifecycleState.detached:
break;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BLoC Counter Example'),
),
body: BlocBuilder<CounterBloc,CounterState>(builder: (context,state){
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Count:', style: TextStyle(fontSize: 20)),
Text(
'${state.count}',
style: TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => context.read<CounterBloc>().add(IncrementEvent()),
child: Text('Increment'),
),
SizedBox(width: 20),
ElevatedButton(
onPressed: () => context.read<CounterBloc>().add(DecrementEvent()),
child: Text('Decrement'),
),
],
),
],
),
);
}));
}
}
总结
在这个简单的例子中,我们创建了一个计数器BLo,处理两个事件:增加和减少。UI部分使用监听状态变化,显示当前计数和两个按钮。BlocBuilder是一个基本的BLoC状态管理示例。你可以根据你的应用程序需求扩展和定制这个模式。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。