【问题标题】:Flutter pass functions to items for list view builderFlutter 将函数传递给列表视图构建器的项目
【发布时间】:2021-05-31 15:39:12
【问题描述】:

我想做的是我有一个带有图标和东西的 ListView,它们就像是应用程序中最常用功能的小快捷方式。

    List _shortcuts = [
    {
      'name': 'HORN',
      'icon': Icons.circle_outlined,
      'selection': false,
      'func': (String dummy) {
        // do something
        print('I did it!' + dummy);
      },
    },
  ].toList();

所以我的问题是......是否可以在 Listviews 构建器方法中调用每个项目的唯一函数?

类似_shortcuts[i]['func']('wow') 的东西?

【问题讨论】:

    标签: flutter dart listview


    【解决方案1】:
    void main() {
      List<Map<String, dynamic>> _short = [
      {
         'name': 'HORN',
          'icon': "Icons.circle_outlined",
          'selection': false,
          'func': (String dummy) { 
           print('I did it! \t' + dummy);
          },
      }
    ];
      
    _short[0]["func"]("hello");
        
    }
    

    希望对您有所帮助。

    【讨论】:

    • 得到这个:处理手势时抛出以下 NoSuchMethodError:闭包调用参数不匹配:函数'new _ShortCutsState.'接收者:闭包:()=>空尝试调用:新_ShortCutsState.("hello") Found: new _ShortCutsState.() => Null
    【解决方案2】:

    您应该创建一个将在您的_shortcuts 列表中使用的类。请看下面的例子:

    // The ShortCut class.
    class ShortCut {
      final String name;
      final IconData icon;
      final bool selection;
      final void Function(String) func;
    
      const ShortCut({
        required this.name,
        required this.icon,
        required this.selection,
        required this.func,
      });
    }
    
    

    这个类可以在小部件中使用,并且可以从ListView小部件的builder方法中访问该函数,如下所示:

    
    class App extends StatefulWidget {
      @override
      _AppState createState() => _AppState();
    }
    
    class _AppState extends State<App> {
      /// The is your list with custom shortcuts.
      final _shortCuts = <ShortCut>[
        ShortCut(
          name: 'HORN',
          icon: Icons.circle_outlined,
          selection: false,
          func: (String dummy) {
            // do something
            print('I did it!' + dummy);
          },
        ),
      ];
    
      @override
      Widget build(BuildContext context) {
        return ListView.builder(
          itemCount: _shortCuts.length,
          itemBuilder: (context, index) {
            final _shortCut = _shortCuts[index];
    
            // Call the function here.
            _shortCut.func('dummy');
    
            return Container();
          },
        );
      }
    }
    
    

    我希望这就是你要找的!

    【讨论】:

      【解决方案3】:

      我认为这应该在 php.ini 中完成。 Dart 做不到。

      【讨论】:

      • 有可能,你应该看看我的代码sn-p。
      猜你喜欢
      • 2011-03-20
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多