【问题标题】:Unable to use the .map function in Flutter无法在 Flutter 中使用 .map 函数
【发布时间】:2021-04-09 10:40:03
【问题描述】:

所以我正在关注一本关于 Flutter 应用程序开发的书,我的任务是实现一个 ToDoMenuItem 类并在其中创建一个列表。

      class TodoMenuItem {
      final String title;
      final Icon icon;
    
      TodoMenuItem({this.title, this.icon});
    
      List<TodoMenuItem> foodMenuList = [
        TodoMenuItem(title: 'Fast Food', icon: Icon(Icons.fastfood)),
        TodoMenuItem(title: 'Remind Me', icon: Icon(Icons.add_alarm)),
        TodoMenuItem(title: 'Flight', icon: Icon(Icons.flight)),
        TodoMenuItem(title: 'Music', icon: Icon(Icons.audiotrack)),
      ];
    }

然后我的任务是使用 itemBuilder 将其映射到 PopUpMenuButtonWidget。这是我为它写的课程。

    class PopupMenuButtonWidget extends StatelessWidget
        implements PreferredSizeWidget {
      const PopupMenuButtonWidget({
        Key key,
      }) : super(key: key);
      @override
      Widget build(BuildContext context) {
        return Container(
          color: Colors.lightGreen.shade100,
          height: preferredSize.height,
          width: double.infinity,
          child: Center(
            child: PopupMenuButton<TodoMenuItem>(
              icon: Icon(Icons.view_list),
              onSelected: ((valueSelected) {
                print('valueSelected: ${valueSelected.title}');
              }),
              itemBuilder: (BuildContext context) {
                return foodMenuList.map((TodoMenuItem todoMenuItem) {
                  return PopupMenuItem<TodoMenuItem>(
                    value: todoMenuItem,
                    child: Row(
                      children: <Widget>[
                        Icon(todoMenuItem.icon.icon),
                        Padding(
                          padding: EdgeInsets.all(8.0),
                        ),
                        Text(todoMenuItem.title),
                      ],
                    ),
                  );
                }).toList();
              },
            ),
          ),
        );
      }
    
      @override // implement preferredSize
      Size get preferredSize => Size.fromHeight(75.0);
    }

但是,它在这一行返回错误。

    return foodMenuList.map((TodoMenuItem todoMenuItem) {

错误提示

Undefined name 'foodMenuList'.
Try correcting the name to one that is defined, or defining the name.

如何将 foodMenuList 列表“映射”到小部件?

【问题讨论】:

    标签: list flutter dart flutter-layout


    【解决方案1】:

    您的foodMenuList 是在todoMenuItem 类中声明的,而您尝试引用它就像它是PopupMenuButtonWidget 的一部分(您在PopupMenuButtonModget 的上下文中执行this.foodMenuList

    您可以在PopupMenuButtonWidget 中创建TodoMenuList 的实例,然后使用它。

    final TodoMenuItem _todoMenu = TodoMenuItem();
    
    Widget build(BuildContext context) {
    ...
    // Someplace where you need to use the list
    _todoMenu.foodMenuList
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2017-10-09
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多