Skip to main content

flowium 1.0.0 copy "flowium: ^1.0.0" to clipboard
flowium: ^1.0.0 copied to clipboard

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

example/lib/main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flowium/flowium.dart';

void main() {
  // Register controllers with dependency injection
  FlowiumDI().registerSingleton<CounterController>(() => CounterController());
  FlowiumDI().registerFactory<TodoController>(() => TodoController());
  
  runApp(const FlowiumExampleApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flowium Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flowium Examples'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          _ExampleCard(
            title: 'Counter Example',
            description: 'Simple counter with Flowium',
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const CounterPage()),
            ),
          ),
          const SizedBox(height: 16),
          _ExampleCard(
            title: 'Todo List',
            description: 'Advanced todo management with async operations',
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const TodoPage()),
            ),
          ),
          const SizedBox(height: 16),
          _ExampleCard(
            title: 'Multi-Controller Demo',
            description: 'Working with multiple controllers',
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const MultiControllerPage()),
            ),
          ),
          const SizedBox(height: 16),
          _ExampleCard(
            title: '🚀 Complete Usage Example',
            description: 'All Flowium features with logging & dev tools',
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const HomePage()),
            ),
          ),
        ],
      ),
    );
  }
}

class _ExampleCard extends StatelessWidget {
  final String title;
  final String description;
  final VoidCallback onTap;

  const _ExampleCard({
    required this.title,
    required this.description,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: Theme.of(context).textTheme.headlineSmall,
              ),
              const SizedBox(height: 8),
              Text(
                description,
                style: Theme.of(context).textTheme.bodyMedium,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// Counter Controller Example
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());
  }
}

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

  @override
  Widget build(BuildContext context) {
    // Get controller from dependency injection
    final controller = context.flowDI<CounterController>();
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('Counter Example'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Center(
        child: FlowiumBuilder<CounterController, FlowiumState>(
          controller: controller,
          builder: (context, state, controller) {
            String countText = '0';
            Color textColor = Colors.black;
            
            if (state is FlowiumSuccess<int>) {
              countText = state.data.toString();
              textColor = state.data > 10 ? Colors.green : Colors.black;
            }
            
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  'Current Count:',
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
                const SizedBox(height: 8),
                Text(
                  countText,
                  style: Theme.of(context).textTheme.displayLarge?.copyWith(
                    color: textColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 24),
                if (state is FlowiumLoading)
                  const CircularProgressIndicator()
                else if (state is FlowiumError)
                  Text(
                    'Error: ${state.message}',
                    style: const TextStyle(color: Colors.red),
                  ),
              ],
            );
          },
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            heroTag: "increment",
            onPressed: controller.increment,
            child: const Icon(Icons.add),
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            heroTag: "decrement",
            onPressed: controller.decrement,
            child: const Icon(Icons.remove),
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            heroTag: "reset",
            onPressed: controller.reset,
            child: const Icon(Icons.refresh),
          ),
        ],
      ),
    );
  }
}

// Todo Controller Example
class Todo {
  final String id;
  final String title;
  final bool completed;
  
  const Todo({
    required this.id,
    required this.title,
    this.completed = false,
  });
  
  Todo copyWith({
    String? id,
    String? title,
    bool? completed,
  }) {
    return Todo(
      id: id ?? this.id,
      title: title ?? this.title,
      completed: completed ?? this.completed,
    );
  }
}

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

class TodoController extends AsyncFlowiumController<FlowiumState> {
  TodoController() : super(const FlowiumInitial());
  
  List<Todo> get todos {
    if (state is TodoState) {
      return (state as TodoState).todos;
    }
    return [];
  }
  
  @override
  void onInit() {
    super.onInit();
    loadTodos();
  }
  
  Future<void> loadTodos() async {
    await executeAsync(
      () async {
        // Simulate API call
        await Future.delayed(const Duration(seconds: 1));
        
        final todos = [
          const Todo(id: '1', title: 'Learn Flowium'),
          const Todo(id: '2', title: 'Build amazing apps'),
          const Todo(id: '3', title: 'Master Flutter state management'),
        ];
        
        emit(TodoState(todos));
      },
      loadingMessage: 'Loading todos...',
      errorMessage: 'Failed to load todos',
    );
  }
  
  void addTodo(String title) {
    if (title.trim().isEmpty) return;
    
    final newTodo = Todo(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      title: title.trim(),
    );
    
    final currentTodos = todos;
    final updatedTodos = [...currentTodos, newTodo];
    emit(TodoState(updatedTodos));
  }
  
  void toggleTodo(String id) {
    final updatedTodos = todos.map((todo) {
      if (todo.id == id) {
        return todo.copyWith(completed: !todo.completed);
      }
      return todo;
    }).toList();
    
    emit(TodoState(updatedTodos));
  }
  
  void deleteTodo(String id) {
    final updatedTodos = todos.where((todo) => todo.id != id).toList();
    emit(TodoState(updatedTodos));
  }
}

class TodoPage extends StatefulWidget {
  const TodoPage({super.key});

  @override
  State<TodoPage> createState() => _TodoPageState();
}

class _TodoPageState extends State<TodoPage> {
  late final TodoController _controller;
  final _textController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    _controller = TodoController();
  }
  
  @override
  void dispose() {
    _controller.dispose();
    _textController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Todo List'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _textController,
                    decoration: const InputDecoration(
                      hintText: 'Enter a new todo...',
                      border: OutlineInputBorder(),
                    ),
                    onSubmitted: (value) {
                      _controller.addTodo(value);
                      _textController.clear();
                    },
                  ),
                ),
                const SizedBox(width: 8),
                IconButton.filled(
                  onPressed: () {
                    _controller.addTodo(_textController.text);
                    _textController.clear();
                  },
                  icon: const Icon(Icons.add),
                ),
              ],
            ),
          ),
          Expanded(
            child: FlowiumStateBuilder<TodoController>(
              controller: _controller,
              loading: (context, message) => const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(height: 16),
                    Text('Loading todos...'),
                  ],
                ),
              ),
              error: (context, message, error) => Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(Icons.error, size: 48, color: Colors.red),
                    const SizedBox(height: 16),
                    Text('Error: $message'),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _controller.loadTodos,
                      child: const Text('Retry'),
                    ),
                  ],
                ),
              ),
              success: (context, data) {
                if (data is! TodoState) return const SizedBox.shrink();
                
                if (data.todos.isEmpty) {
                  return const Center(
                    child: Text('No todos yet. Add one above!'),
                  );
                }
                
                return ListView.builder(
                  itemCount: data.todos.length,
                  itemBuilder: (context, index) {
                    final todo = data.todos[index];
                    return ListTile(
                      leading: Checkbox(
                        value: todo.completed,
                        onChanged: (value) {
                          _controller.toggleTodo(todo.id);
                        },
                      ),
                      title: Text(
                        todo.title,
                        style: TextStyle(
                          decoration: todo.completed
                              ? TextDecoration.lineThrough
                              : TextDecoration.none,
                        ),
                      ),
                      trailing: IconButton(
                        icon: const Icon(Icons.delete, color: Colors.red),
                        onPressed: () {
                          _controller.deleteTodo(todo.id);
                        },
                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

// Multi-Controller Example
class TimerController extends FlowiumController<FlowiumState> {
  TimerController() : super(const FlowiumInitial());
  
  int _seconds = 0;
  Timer? _timer;
  
  int get seconds => _seconds;
  
  void startTimer() {
    if (_timer?.isActive ?? false) return;
    
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _seconds++;
      emit(FlowiumSuccess(_seconds));
    });
  }
  
  void stopTimer() {
    _timer?.cancel();
    emit(const FlowiumInitial());
  }
  
  void resetTimer() {
    _timer?.cancel();
    _seconds = 0;
    emit(const FlowiumInitial());
  }
  
  @override
  void onDispose() {
    _timer?.cancel();
    super.onDispose();
  }
}

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

  @override
  Widget build(BuildContext context) {
    return FlowiumMultiProvider(
      providers: [
        FlowiumProvider(
          controller: CounterController(),
          child: const SizedBox.shrink(),
        ),
        FlowiumProvider(
          controller: TimerController(),
          child: const SizedBox.shrink(),
        ),
      ],
      child: const MultiControllerContent(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Multi-Controller Demo'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // Counter Section
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    const Text(
                      'Counter Controller',
                      style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 16),
                    FlowiumBuilder<CounterController, FlowiumState>(
                      controller: context.flow<CounterController>(),
                      builder: (context, state, controller) {
                        int count = 0;
                        if (state is FlowiumSuccess<int>) {
                          count = state.data;
                        }
                        
                        return Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            IconButton.filled(
                              onPressed: controller.decrement,
                              icon: const Icon(Icons.remove),
                            ),
                            Text(
                              '$count',
                              style: const TextStyle(fontSize: 24),
                            ),
                            IconButton.filled(
                              onPressed: controller.increment,
                              icon: const Icon(Icons.add),
                            ),
                          ],
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            // Timer Section
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    const Text(
                      'Timer Controller',
                      style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 16),
                    FlowiumBuilder<TimerController, FlowiumState>(
                      controller: context.flow<TimerController>(),
                      builder: (context, state, controller) {
                        int seconds = 0;
                        if (state is FlowiumSuccess<int>) {
                          seconds = state.data;
                        }
                        
                        return Column(
                          children: [
                            Text(
                              '${seconds}s',
                              style: const TextStyle(fontSize: 32),
                            ),
                            const SizedBox(height: 16),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                ElevatedButton(
                                  onPressed: controller.startTimer,
                                  child: const Text('Start'),
                                ),
                                ElevatedButton(
                                  onPressed: controller.stopTimer,
                                  child: const Text('Stop'),
                                ),
                                ElevatedButton(
                                  onPressed: controller.resetTimer,
                                  child: const Text('Reset'),
                                ),
                              ],
                            ),
                          ],
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            // Combined State Display
            FlowiumMultiConsumer(
              controllers: [
                context.flow<CounterController>(),
                context.flow<TimerController>(),
              ],
              builder: (context, controllers) {
                final counterController = controllers[0] as CounterController;
                final timerController = controllers[1] as TimerController;
                
                int counterValue = 0;
                if (counterController.state is FlowiumSuccess<int>) {
                  counterValue = (counterController.state as FlowiumSuccess<int>).data;
                }
                
                int timerValue = 0;
                if (timerController.state is FlowiumSuccess<int>) {
                  timerValue = (timerController.state as FlowiumSuccess<int>).data;
                }
                
                return Card(
                  color: Colors.blue.shade50,
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      children: [
                        const Text(
                          'Combined State',
                          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 8),
                        Text('Counter × Timer = ${counterValue * timerValue}'),
                        Text('Counter + Timer = ${counterValue + timerValue}'),
                      ],
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
0
likes
150
points
32
downloads

Documentation

Documentation
API reference

Publisher

unverified uploader

Weekly Downloads

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

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter, meta

More

Packages that depend on flowium