Getting Started with RxDart: A Beginner's Guide to Reactive Programming in Dart

 This code is a simple Flutter application that demonstrates the use of RxDart, a reactive programming library for Dart. The app consists of a single screen that displays a counter and a button to increment the counter.


import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'RxDart demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late final MyHomePageController _controller;

  @override
  void initState() {
    super.initState();
    _controller = MyHomePageController();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<int>(
      stream: _controller.counterStream,
      builder: (context, snapshot) => Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '${snapshot.data}',
                style: Theme.of(context).textTheme.headline6,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _controller.incrementCounter(),
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

class MyHomePageController {
  final _counterSubject = BehaviorSubject<int>.seeded(0);

  Stream<int> get counterStream => _counterSubject.stream;

  void incrementCounter() {
    _counterSubject.add(_counterSubject.value + 1);
  }

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

Here is a brief explanation of the code:

  • The first two lines import the required packages, flutter/material.dart for the UI elements and rxdart/rxdart.dart for the reactive programming library.
  • The main() function runs the app by creating an instance of the MyApp widget and passing it to the runApp() function.
  • The MyApp class is a stateless widget that returns a MaterialApp widget, which is the root of the app. It sets the app title and theme and specifies the home page to be an instance of the MyHomePage widget.
  • The MyHomePage class is a stateful widget that displays the counter and the button to increment it. It also defines the _MyHomePageState class as its state, which holds an instance of the MyHomePageController class.
  • The MyHomePageController class is a simple controller class that uses the BehaviorSubject class from RxDart to hold the counter value and expose it as a stream. It also provides a method to increment the counter and a dispose() method to close the stream when the widget is disposed.
  • The build() method of _MyHomePageState returns a StreamBuilder widget, which listens to changes in the counter stream and updates the UI accordingly. The AppBar, Text, and FloatingActionButton widgets are defined inside the Scaffold widget, which is the main container for the UI elements of the page.

Overall, this app demonstrates how to use RxDart to implement a simple reactive programming pattern in a Flutter app.

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

How to Make a Dynamic and Trending ListView with Flutter Widgets?

Understanding API integration with Getx State management