Generate random List data to use with Listview.Builder

Sometimes, when backend is not ready, you want to test your app which using ListView or GridView. In such case, you can generate random data using flutter inbuilt List generation function.

In this screenshot you are seeing that we generate some random users with radom offline and online status. Will you believe that this data is generated using just single line of code. So lets start.

Just generate the random data using the following code.

Syntax

The below code returns a dynamic value. you can return any data type.

List.generate(length, (index) => returnSomeValue);

Or you can also explicit give your data type. I’ve given String and it should also return a String.

List.generate(length, (index) => “String”);

Now lets dive on the code part.

List<Map> generatedList = List<Map>.generate(
        20, (i) => {'username': 'john$i', 'email': 'john$i@example.com', "mobiles": List<String>.generate(2, (index) => "9999${Random().nextInt(1000000)}"),"isOnline": Random().nextBool()});

In this code, I’ve created a List<Map> which i can use to create a list of yours.

Now you can use generatedList variable to your ListView.

complete code

import 'dart:math';
import 'package:flutter/material.dart';
class GenerateList extends StatefulWidget {
const GenerateList({super.key});
@override
State<GenerateList> createState() => _GenerateListState();
}
class _GenerateListState extends State<GenerateList> {
List<Map> generatedList = [];
@override
void initState() {
super.initState();
generateList();
}
void generateList() {
generatedList = List<Map>.generate(
20,
(i) => {
'username': 'tom$i',
'email': 'tom$i@example.com',
"mobiles": List<String>.generate(
2, (index) => "9999${Random().nextInt(1000000)}"),
"isOnline": Random().nextBool()
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Generate Random List"),
),
body: SingleChildScrollView(
child: Column(
children: [
generatedList.isNotEmpty
? ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: generatedList.length,
itemBuilder: (context, index) => Column(
children: [
Column(
children: [
ListTile(
leading: const Icon(Icons.account_circle),
title: Text(generatedList[index]["username"]),
trailing: Icon(
Icons.circle,
color: generatedList[index]["isOnline"]
? Colors.green
: Colors.red,
size: 15,
),
subtitle: Text(generatedList[index]["email"]),
)
],
),
const SizedBox(
height: 10,
),
],
))
: Container(),
],
),
),
);
}
}

Video Output

Leave a Reply