🎢Collection data

Management of collection data such as List, Set, Map.

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

Usage

Pulse-X has provided you with three different collection view models. You can use each of them as you need.

  1. PulseXListViewModel

  2. PulseXSetViewModel

  3. PulseXMapViewModel

Example 1 - PulseXListViewModel

Let's create a random user list generator using Pulse.

First you have to addfaker package which generate users in your pubspec.yaml file dependencies: section.

Create a UserModel class to create user model.

class UserModel {
  String name;
  String age;
  String job;
  String city;
  UserModel({
    required this.name,
    required this.age,
    required this.job,
    required this.city,
  });
}

Then, create a service that returns a new user. Here, I'll use abstraction to obey Open/Close Principle.

abstract class IUserService{
  UserModel getNewUser();
}

class UserServiceImpl extends IUserService {
  final faker = Faker();
  @override
  UserModel getNewUser() {
    String city = faker.address.city();
    String name = faker.person.name();
    DateTime birthDate =
        faker.date.dateTimeBetween(DateTime(1940), DateTime.now());
    int age = DateTime.now().year - birthDate.year;
    String job = faker.job.title();
    return UserModel(
      name: name,
      age: age.toString(),
      job: job,
      city: city,
    );
  }
}

class UserServiceImpl extends IUserService {
  final faker = Faker();
  @override
  UserModel getNewUser() {
    String city = faker.address.city();
    String name = faker.person.name();
    DateTime birthDate =
        faker.date.dateTimeBetween(DateTime(1940), DateTime.now());
    int age = DateTime.now().year - birthDate.year;
    String job = faker.job.title();
    return UserModel(
      name: name,
      age: age.toString(),
      job: job,
      city: city,
    );
  }
}

After that, you are ready to create a ViewModel which extends Pulse's PulseListViewModel. We'll pass IUserService in constructor to do dependency inversion.


class UsersViewModel extends PulseListViewModel<UserModel> { // specify your data type so that you won't get confused with type conversion
  final IUserService service;
  UsersViewModel({
    required this.service,
  });

  void addUser() {
    UserModel user = service.getNewUser();
    addValue(user); // when you want to add something, use `addValue(T)` method from Pulse
    // it'll automatically add your data to list
  }
}

Lastly, we'll have to create a view that shows a list of users.

class UsersView extends StatelessWidget {
  UsersView({Key? key}) : super(key: key);
  final viewModel = UsersViewModel(service: UserServiceImpl()); // initialize your view model, later we'll use Pulse's service locator
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Users'),
      ),
      body: PulseBuilder( // reactive when added a new user
        viewModel: viewModel,
        builder: (context, model, _) {
          return model.value.isEmpty
              ? const Center(
                  child: Text('No users created!'),
                )
              : GridView.builder(
                  padding: const EdgeInsets.only(bottom: 80),
                  addAutomaticKeepAlives: true,
                  addRepaintBoundaries: true,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                  ),
                  itemCount: model.value.length,
                  itemBuilder: (context, index) {
                    UserModel user = model.value[index];
                    return Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16.0),
                        color: Colors.amber.shade200,
                      ),
                      margin: const EdgeInsets.all(8.0),
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Text(
                            user.name,
                            maxLines: 8,
                            style: Theme.of(context).textTheme.titleMedium,
                          ),
                          Text(
                            '${user.age} years',
                          ),
                          Text(
                            user.job,
                            textAlign: TextAlign.center,
                          ),
                          Text(
                            user.city,
                          ),
                        ],
                      ),
                    );
                  },
                );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: viewModel.addUser, // add a new user 
        child: const Icon(Icons.person_add_alt_rounded),
      ),
    );
  }
}

🍾Congratulations!! You've completed list data management with Pulse.

Complete source code can be found here. https://github.com/YeLwinOo-Steve/rand_user

🚧 Set and map management examples are coming soon .....

Last updated