DEV Community

Cover image for A month of Flutter: real faker data
Abraham Williams
Abraham Williams

Posted on • Originally published at bendyworks.com

A month of Flutter: real faker data

Originally published on bendyworks.com.

Yesterday I left the code base with failing tests because the fixture data stored in a JSON file can't be read in Flutter tests. Today I'm going to complete the move to streamed mock data by switching from static fixtures to dynamic factories in a Dart file. The Unsplash image IDs will still be hard coded but the rest of the values will be dynamically generated.

The core of the work will be performed in mockPostData. This will create a Map with a random UUID from the uuid package, a random image ID from the pre-selected list, a DateTime, and random text and username with the faker package.

I have added a day between each DateTime value, so if I generate three posts, they will be from today, yesterday, and two days ago, respectively.

Map<String, dynamic> mockPostData({int index = 0}) {
  const Faker faker = Faker();
  final String imageId = faker.randomGenerator.element(imageIds);
  final String createdAt =
      DateTime.now().subtract(Duration(days: index)).toIso8601String();

   return <String, dynamic>{
    'id': Uuid().v4(),
    'imageUrl': 'https://source.unsplash.com/$imageId',
    'createdAt': createdAt,
    'text': faker.conference.name(),
    'username': faker.person.name()
  };
}
~~~{% endraw %}

There are also two helper methods, {% raw %}`mockPost`{% endraw %} and {% raw %}`mockPosts`{% endraw %}, to wrap the raw data in {% raw %}`Post`{% endraw %} instances. Now it's just a matter of updating the tests and the {% raw %}`_loadPosts` function to use the new mock methods.

Using faker to generate mock data results in different names showing up.

![Screenshot of random mock usernames](https://thepracticaldev.s3.amazonaws.com/i/aa14o8mhqjrkjh9y5xrg.png)

This is the base mock data rendering. Tomorrow starts the fun work of rendering the actual images.

## Code changes

- [#29 Turn mock posts into Stream](https://github.com/abraham/birb/pull/29)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)