Now Reading: GetX vs BLoC in Flutter – code example simple counter App

Loading

GetX vs BLoC in Flutter – code example simple counter App

svgFebruary 17, 2023DartFlutterCodeStackGuide

GetX and BLoC are both popular state management solutions for Flutter apps, but they have different approaches and functionality. Here are some of the key differences between GetX and BLoC:

GetX:

  • Provides a complete set of tools for state management, dependency injection, routing, and more in a single package
  • Uses a reactive programming model based on Rx (ReactiveX)
  • Has a lightweight syntax and high performance
  • Suitable for large and complex apps with advanced state management needs
  • Provides a simple and intuitive syntax for updating and accessing state

BLoC:

  • Stands for Business Logic Component
  • Uses streams to manage and update state
  • Provides a way to separate business logic from UI and presentation logic
  • Has a well-defined architecture and structure
  • Suitable for apps with complex business logic and data processing needs
  • Provides good separation of concerns and testability

Here are some code examples of using GetX for state management:

// Define a controller to manage the state
class CounterController extends GetxController {
  var counter = 0.obs;

  void incrementCounter() {
    counter++;
  }
}

// Use the controller in a widget to access the shared data
class MyWidget extends StatelessWidget {
  final CounterController controller = Get.put(CounterController());

  @override
  Widget build(BuildContext context) {
    return Text('Counter: ${controller.counter}');
  }
}

// Update the shared data using the controller
class MyButton extends StatelessWidget {
  final CounterController controller = Get.find();

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        controller.incrementCounter();
      },
      child: Text('Increment'),
    );
  }
}

Here is an example of using BLoC for state management in a simple counter app:





// Define an event class for the counter updates
abstract class CounterEvent {}

class IncrementCounterEvent extends CounterEvent {}

// Define a state class for the counter
class CounterState {
  final int counter;

  CounterState({this.counter});

  factory CounterState.initial() => CounterState(counter: 0);
}

// Define a BLoC class to manage the counter state
class CounterBloc {
  final _counterController = StreamController<CounterState>.broadcast();
  int _counter = 0;

  Stream<CounterState> get counterStream => _counterController.stream;

  void mapEventToState(CounterEvent event) {
    if (event is IncrementCounterEvent) {
      _counter++;
      _counterController.add(CounterState(counter: _counter));
    }
  }

  void dispose() {
    _counterController.close();
  }
}

// Use the BLoC in a widget to access the shared data
class CounterScreen extends StatefulWidget {
  @override
  _CounterScreenState createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  final _counterBloc = CounterBloc();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter App')),
      body: StreamBuilder<CounterState>(
        stream: _counterBloc.counterStream,
        initialData: CounterState.initial(),
        builder: (context, snapshot) {
          return Center(
            child: Text('Counter: ${snapshot.data.counter}'),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _counterBloc.mapEventToState(IncrementCounterEvent());
        },
        child: Icon(Icons.add),
      ),
    );
  }

  @override
  void dispose() {
    _counterBloc.dispose();
    super.dispose();
  }
}

In this example, we define a CounterBloc class to manage the counter state using streams. We define an IncrementCounterEvent class to trigger updates to the counter, and a CounterState class to hold the current counter value. We use a StreamBuilder widget to listen to the stream of counter states and update the UI accordingly.

Note that this is just a basic example, and there are many different ways to use BLoC for state management depending on your specific needs.

0 People voted this article. 0 Upvotes - 0 Downvotes.
svg

What do you think?

Show comments / Leave a comment

47 Comments:

Leave a reply

svg
Quick Navigation
  • 01

    GetX vs BLoC in Flutter – code example simple counter App