💡Simple data

Guide to use simple data such as int, double, string, custom classes,etc.

Use tip: At first, you'll have to install Pulse-X package. Here's the installation tip.

Usage

Pulse-X works in MVVM structure. So, you'll have to extend our ViewModel. Here, view and view model don't need to be a single screen. They can be widgets, also. So, you can reuse each view and view model. There are multiple types of view models.

  • PulseXViewModel (for simple data)

  • PulseXListViewModel (for list data)

  • PulseXSetViewModel (for set data)

  • PulseXMapViewModel (for map data)

  • PulseXFutureViewModel (for future data)

  • PulseXStreamViewModel (for stream data)

Here in this counter example, we'll use simple data with PulseXViewModel.

import 'package:pulse_x/pulse_x.dart';

class CounterViewModel extends PulseXViewModel<int> {
  CounterViewModel() : super(0);

  void increment() {
    value++;
  }

  void decrement() {
    value--;
  }
}

Done!! Ez, isn't it?? 🥳

You've already learned how to use Pulse-X view model.

Here, You can specify your data type in PulseXViewModel<T>. T can be int, double,string, custom classes,etc. Then, you'll be forced to call super(T) with initial value to avoid null exception. You don't need to use any other variables. You can use only value. You can update value and it'll automatically reflect changes to UI.

In UI part, you can use stateless widget without worrying about state update. Here's the code.

import 'package:flutter/material.dart';

class CounterView extends StatelessWidget{
    @override
    Widget build(BuildContext context){
    return Scaffold(
        appBar: AppBar(title: Text('Counter')),
        body: Center(
        child: PulseBuilder(
            viewModel: CounterViewModel(),
            builder: (context, viewModel, child){
                return Text('${viewModel.value}');
            }
          ),
        ),
        floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            heroTag: 'increment',
            onPressed: counterViewModel.increment,
            child: const Icon(
              Icons.add,
            ),
          ),
          const SizedBox(
            width: 30,
          ),
          FloatingActionButton(
            heroTag: 'decrement',
            onPressed: counterViewModel.decrement,
            child: const Icon(
              Icons.remove,
            ),
          ),
        ],
      ),
    );
    }
}

To make your view reactive, you have to wrap your widget with PulseXBuilder. It takes two parameters - your view model and builder function. Builder function has three parameters - context, viewModel, child. Here, you can access your data by calling viewModel.value. That's it.

🥳 Congratulations!! You've successfully learnt how to manage simple data using Pulse-X. Next is collection data.

Last updated