Search code examples
listflutterdartdart-null-safety

Flutter 2: From List null safety create a children row with mapIndex


Since the update of flutter of null safety I don't understand anything of what is happening.

I am trying from a list on a children to create a Row of icons but I don't succeed (here the mapIndex can't be used because of the null safety (whereas in an older version it would worked)):

import 'package:flutter/material.dart';

class NavigationBar extends StatefulWidget {
  final List<Map<String, dynamic>>? icons;

  const NavigationBar({
    @required this.icons,
    Key? key
  }) : super(key: key);

  @override
  _NavigationBarState createState() => _NavigationBarState();
}

class _NavigationBarState extends State<NavigationBar> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 40,
      child: Row(
        children: widget.icons.mapIndex((i, icon) {return Container();})
      ),
    );
  }
}

Solution

  • The first problem was the missing of the collection import (so I couldn't use mapIndex)

    The second is the verification of the null. I don't know if it is the better solution but here my version where I check the null value :

    import 'package:flutter/material.dart';
    
    import 'package:collection/collection.dart';
    
    class NavigationBar extends StatefulWidget {
      final List<Map<String, dynamic>>? icons;
    
      const NavigationBar({
        @required this.icons,
        Key? key
      }) : super(key: key);
    
      @override
      _NavigationBarState createState() => _NavigationBarState();
    }
    
    class _NavigationBarState extends State<NavigationBar> {
      @override
      Widget build(BuildContext context) {
        return Container(
          color: Color.fromARGB(255, 12, 10, 10),
          width: double.infinity,
          height: 40,
          child: Row(
            children: widget.icons == null ? [] :
              widget.icons!.mapIndexed((index, element) =>
              IconButton(
                onPressed: () {},
                icon: widget.icons![0]['icon'],
                color: Colors.white,
              )).toList()
          ),
        );
      }
    }