Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert 'SizedBox' widgets in the list of 'FaIcon' widgets?

I am trying to create a widget which replaces string of numbers into a row of correlated icons. That much is working great. But I want to have some gap between those icons. I am trying to use ‘SizedBox’ to achieve it. But I get an error – "type ‘SizedBox’ is not a subtype of type ‘FaIcon’ of ‘element’". What’s happening here?

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class NumberIcons extends StatelessWidget {
  const NumberIcons({
    super.key,
    required this.numberString,
    required this.color,
    this.size = 12,
    this.gap = 1,
  });

  final String numberString;
  final Color color;
  final double size;
  final double gap;

  @override
  Widget build(BuildContext context) {
    Map<String, IconData> iconsMap = {
      '1': FontAwesomeIcons.one,
      '2': FontAwesomeIcons.two,
      '3': FontAwesomeIcons.three,
      '4': FontAwesomeIcons.four,
      '5': FontAwesomeIcons.five,
      '6': FontAwesomeIcons.six,
      '7': FontAwesomeIcons.seven,
      '8': FontAwesomeIcons.eight,
      '9': FontAwesomeIcons.nine,
      '0': FontAwesomeIcons.zero,
    };

    List<Widget> iconsList = numberString
        .split('')
        .map(
          (digitString) => FaIcon(
            iconsMap[digitString]!,
            color: color,
            size: size,
          ),
        )
        .toList();

    iconsList;

    for (int i = iconsList.length - 1; i > 0; i--) {
      iconsList.insert(i, SizedBox(width: gap)); // this line is responsible for the error
    }

    return Row(
      children: iconsList,
    );
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Even though you type annotated iconsList with List<Widget>, the assigned list on the right-hand side is a List<FaIcon> at runtime. You should specify the generic type to the map method:

List<Widget> iconsList = numberString
    .split('')
    .map<Widget>( // Change this line
      (digitString) => FaIcon(
        iconsMap[digitString]!,
        color: color,
        size: size,
      ),
    )
    .toList();

Alternatively, you can use SeparatedRow from package flextras to achieve that.

SeparatedRow(
  separatorBuilder: () => SizedBox(width: gap),
  children: iconsList,
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading