Flowium

Flutter Dart License

A powerful yet simple Flutter state management package that combines the power of BLoC with the simplicity of GetX. Flowium is lightweight, performant, and developer-friendly.

โœจ Features

  • ๐Ÿš€ Simple & Intuitive - Easy to learn and use, minimal boilerplate
  • โšก High Performance - Optimized for minimal rebuilds and memory usage
  • ๐Ÿ—๏ธ Type Safe - Full type safety with generics
  • ๐Ÿ”„ Async Support - Built-in async state handling and error management
  • ๐Ÿ’‰ Dependency Injection - Simple and powerful DI system
  • ๐ŸŽฏ Selective Rebuilds - Fine-grained control over widget rebuilds
  • ๐Ÿงช Testable - Easy to unit test and mock
  • ๐Ÿ“ฑ Flutter Ready - Works seamlessly with Flutter's widget tree

๐Ÿ“ฆ Installation

Add this to your package's pubspec.yaml file:

dependencies:
  flowium: ^1.0.0

Then run:

flutter pub get

๐Ÿš€ Quick Start

1. Create a Controller

import 'package:flowium/flowium.dart';

class CounterController extends FlowiumController<FlowiumState> {
  CounterController() : super(const FlowiumInitial());
  
  int _count = 0;
  
  int get count => _count;
  
  void increment() {
    _count++;
    emit(FlowiumSuccess(_count));
  }
  
  void decrement() {
    _count--;
    emit(FlowiumSuccess(_count));
  }
  
  void reset() {
    _count = 0;
    emit(const FlowiumInitial());
  }
}

2. Provide the Controller

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return FlowiumProvider(
      controller: CounterController(),
      child: MaterialApp(
        title: 'Flowium Demo',
        home: const CounterPage(),
      ),
    );
  }
}

3. Build the UI

class CounterPage extends StatelessWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = context.flow<CounterController>();
    
    return Scaffold(
      appBar: AppBar(title: const Text('Flowium Counter')),
      body: Center(
        child: FlowiumBuilder<CounterController, FlowiumState>(
          controller: controller,
          builder: (context, state, controller) {
            if (state is FlowiumSuccess<int>) {
              return Text(
                '${state.data}',
                style: Theme.of(context).textTheme.headlineMedium,
              );
            }
            return const Text('0');
          },
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            onPressed: controller.increment,
            child: const Icon(Icons.add),
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            onPressed: controller.decrement,
            child: const Icon(Icons.remove),
          ),
        ],
      ),
    );
  }
}

๐Ÿ“š Core Concepts

Controllers

Controllers are the heart of Flowium. They manage state and business logic:

class UserController extends AsyncFlowiumController<FlowiumState> {
  UserController() : super(const FlowiumInitial());
  
  Future<void> fetchUser(String userId) async {
    await executeAsync(
      () async {
        final user = await ApiService.getUser(userId);
        emit(FlowiumSuccess(user));
      },
      loadingMessage: 'Fetching user...',
      errorMessage: 'Failed to fetch user',
    );
  }
}

States

Flowium provides built-in state classes:

  • FlowiumInitial - Initial state
  • FlowiumLoading - Loading state with optional message
  • FlowiumSuccess<T> - Success state with data
  • FlowiumError - Error state with message and details

Widgets

FlowiumBuilder

Rebuilds when controller state changes:

FlowiumBuilder<MyController, MyState>(
  controller: controller,
  builder: (context, state, controller) {
    return Text('Current state: $state');
  },
)

FlowiumConsumer

More control over when to rebuild:

FlowiumConsumer<MyController, MyState>(
  controller: controller,
  rebuildWhen: (previous, current) => previous.data != current.data,
  builder: (context, state, controller) {
    return MyWidget(data: state.data);
  },
)

FlowiumStateBuilder

Specialized builder for different state types:

FlowiumStateBuilder<MyController>(
  controller: controller,
  loading: (context, message) => CircularProgressIndicator(),
  error: (context, message, error) => Text('Error: $message'),
  success: (context, data) => Text('Success: $data'),
)

Dependency Injection

Flowium provides a simple DI system:

// Register dependencies
void main() {
  FlowiumDI().registerSingleton<CounterController>(() => CounterController());
  FlowiumDI().registerFactory<UserController>(() => UserController());
  
  runApp(MyApp());
}

// Use in widgets
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final controller = context.flowDI<CounterController>();
    return Text('${controller.count}');
  }
}

๐Ÿ—๏ธ Advanced Usage

Custom States

Create your own state classes:

class CounterState extends FlowiumState {
  final int count;
  
  const CounterState(this.count);
  
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is CounterState && runtimeType == other.runtimeType && count == other.count;
  
  @override
  int get hashCode => count.hashCode;
}

class CounterController extends FlowiumController<CounterState> {
  CounterController() : super(const CounterState(0));
  
  void increment() => emit(CounterState(state.count + 1));
}

Multiple Controllers

Manage multiple controllers easily:

FlowiumMultiProvider(
  providers: [
    FlowiumProvider(controller: CounterController()),
    FlowiumProvider(controller: UserController()),
  ],
  child: MyPage(),
)

// Or use FlowiumMultiConsumer
FlowiumMultiConsumer(
  controllers: [counterController, userController],
  builder: (context, controllers) {
    final counter = controllers[0] as CounterController;
    final user = controllers[1] as UserController;
    return Column(
      children: [
        Text('Count: ${counter.count}'),
        Text('User: ${user.name}'),
      ],
    );
  },
)

Selective Rebuilds

Optimize performance with selective consumers:

FlowiumSelectiveConsumer<CounterController, CounterState, int>(
  controller: controller,
  selector: (state) => state.count,
  builder: (context, count, controller) {
    return Text('$count'); // Only rebuilds when count changes
  },
)

๐Ÿงช Testing

Flowium is designed to be testable:

void main() {
  group('CounterController', () {
    late CounterController controller;
    
    setUp(() {
      controller = CounterController();
    });
    
    tearDown(() {
      controller.dispose();
    });
    
    test('initial state is correct', () {
      expect(controller.state, isA<FlowiumInitial>());
    });
    
    test('increment updates state', () {
      controller.increment();
      expect(controller.state, isA<FlowiumSuccess<int>>());
      expect((controller.state as FlowiumSuccess<int>).data, 1);
    });
  });
}

๐Ÿ“– API Reference

FlowiumController

The base controller class for state management.

Methods

  • emit(T state) - Emit a new state
  • updateState(T Function(T) transformer) - Update state with transformer
  • setLoading([String? message]) - Set loading state
  • setError(String message) - Set error state
  • init() - Initialize the controller
  • dispose() - Dispose the controller

Properties

  • T state - Current state
  • bool isDisposed - Whether controller is disposed
  • int listenerCount - Number of listeners

FlowiumBuilder

Widget that rebuilds based on controller state.

Parameters

  • T controller - The controller to listen to
  • Widget Function(BuildContext, S, T) builder - Builder function
  • Widget Function(BuildContext)? placeholder - Optional placeholder
  • bool autoInit - Auto-initialize controller

FlowiumConsumer

Widget with fine-grained rebuild control.

Parameters

  • T controller - The controller to listen to
  • Widget Function(BuildContext, S, T) builder - Builder function
  • bool Function(S, S)? rebuildWhen - Rebuild condition
  • bool autoInit - Auto-initialize controller

FlowiumDI

Dependency injection system.

Methods

  • registerSingleton<T>(T Function(), {bool lazy}) - Register singleton
  • registerFactory<T>(T Function()) - Register factory
  • registerInstance<T>(T instance) - Register instance
  • T get<T>() - Get dependency
  • T? getOrNull<T>() - Get dependency or null
  • bool isRegistered<T>() - Check if registered
  • unregister<T>() - Unregister dependency
  • clear() - Clear all dependencies

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Inspired by BLoC pattern and GetX simplicity
  • Built with โค๏ธ for the Flutter community

๐Ÿ“ž Support

If you have any questions or need help, please:


Flowium - Making Flutter state management simple and powerful! ๐Ÿš€

Libraries

flowium
Flowium - A powerful yet simple Flutter state management package