当前位置:   article > 正文

一个Flutter BLoC入门的简单 demo

一个Flutter BLoC入门的简单 demo

通过一个非常简单的计数器示例来演示如何使用BLoC模式。这个计数器将有增加和减少两个功能。

步骤 1: 添加依赖

首先,确保你的Flutter项目中添加了flutter_bloc依赖。在你的pubspec.yaml文件中添加:

dependencies:
  flutter_bloc: ^8.0.1 # 请检查最新版本
  flutter:
    sdk: flutter

  • 1
  • 2
  • 3
  • 4
  • 5

然后运行flutter pub get来安装依赖。

步骤 2: 创建CounterEvent

创建一个counter_event.dart文件,这个文件将包含我们的事件类。对于计数器,我们将有两个事件:增加和减少。

abstract class CounterEvent {}

class CounterIncrementPressed extends CounterEvent {}

class CounterDecrementPressed extends CounterEvent {}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

步骤 3: 创建CounterState

接着,创建一个counter_state.dart文件,这个文件将定义计数器的状态。

class CounterState {
  final int counterValue;

  CounterState({required this.counterValue});
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

步骤 4: 创建CounterBloc

现在,创建counter_bloc.dart,这是核心部分,它将处理事件并更新状态。

import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_event.dart';
import 'counter_state.dart';

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  CounterBloc() : super(CounterState(counterValue: 0)) {
    on<CounterIncrementPressed>((event, emit) {
      emit(CounterState(counterValue: state.counterValue + 1));
    });

    on<CounterDecrementPressed>((event, emit) {
      emit(CounterState(counterValue: state.counterValue - 1));
    });
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

步骤 5: 使用BlocBuilder来构建UI

最后,在main.dart或其他任何你想要显示计数器的地方,使用BlocProvider和BlocBuilder来构建UI。

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_bloc.dart';
import 'counter_event.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BlocProvider(
        create: (context) => CounterBloc(),
        child: CounterPage(),
      ),
    );
  }
}

class CounterPage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter')),
      body: Center(
        child: BlocBuilder<CounterBloc, CounterState>(
          builder: (context, state) {
            return Text(
              '${state.counterValue}',
              style: Theme.of(context).textTheme.headline4,
            );
          },
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () => context.read<CounterBloc>().add(CounterIncrementPressed()),
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
          SizedBox(height: 10),
          FloatingActionButton(
            onPressed: () => context.read<CounterBloc>().add(CounterDecrementPressed()),
            tooltip: 'Decrement',
            child: Icon(Icons.remove),
          ),
        ],
      ),
    );
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

这个简单的计数器应用演示了BLoC模式的基本使用:定义事件(CounterEvent)、状态(CounterState)和业务逻辑组件(CounterBloc),然后在UI层通过BlocBuilder根据状态变化来构建相应的UI。通过这种方式,可以将业务逻辑与UI表示分离,使得代码更加模块化和易于管理。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/227186
推荐阅读
相关标签
  

闽ICP备14008679号