'How generate specific widget dynamically inside ListView.Builder?

How generate specific widget dynamically inside ListView.Builder?

I have my data coming from StreamBuilder, this data coming in numbers [1...24] sometimes coming just number [3] or [2,4,7,8,11,12] I'm trying to build 24 containers with a ListView.builder inside StreamBuilder and assign these values.

I need to create 24 containers and assign them my values from my StreamBuilder.

enter image description here

I need something like attached image. The whites numbers are additional, black numbers are my data in my Stream.



Solution 1:[1]

Copy this code below and paste to dartpad to run full example

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:math';
import 'dart:async';

void main() {
  return runApp(const MaterialApp(home: MyHomePage(slots: 24)));
}

class MyHomePage extends StatefulWidget {
  final int slots;
  const MyHomePage({Key? key, required this.slots}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Stream<List<int>> source;

  @override
  void initState() {
    source = Stream<List<int>>.periodic(const Duration(seconds: 1), (i) {
      final rnd = Random();
      final length = rnd.nextInt(widget.slots);
      return (List.generate(widget.slots - 1, (i) => i + 1)..shuffle())
          .sublist(0, length);
    }).take(1000);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: StreamBuilder<List<int>>(
        stream: source,
        builder: (context, snapshot) {
          final data = snapshot.hasData ? snapshot.data ?? [] : [];
          return Column(
            children: [
              Text('slots: ${widget.slots}'),
              Text('filed: $data'),
              Wrap(
                children: List.generate(widget.slots, (i) {
                  final isActive = data.contains(i);
                  return Container(
                    width: 80,
                    height: 40,
                    margin: const EdgeInsets.all(3),
                    color: Colors.amberAccent,
                    child: Text('$i',
                        style: TextStyle(
                            color: isActive ? Colors.black : Colors.white)),
                  );
                }),
              ),
            ],
          );
        },
      ),
    );
  }
}

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tuan