【问题标题】:How do you pass a MaterialPageRoute to a Widget如何将 MaterialPageRoute 传递给 Widget
【发布时间】:2021-05-02 08:34:08
【问题描述】:

我正在尝试制作一个带有手势检测器的小部件,当您按下它时会打开一个 MaterialPageRoute。在 build 方法中,我要输入 3 个构造函数,一个标签,一个图标,最后是路由。标签和图标都可以正常工作。我不确定要使用哪种变量或链接的语法。总的来说,我对 Flutter 和编程还是很陌生。

按下时,此代码中的“ToolMaker”应导航到我指定的 MaterialPageRoute,在本例中为 ScoreKeeper()。下面的代码给了我一个错误“参数类型'ScoreKeeper'不能分配给参数类型'Navigator'”

'''

class ToolsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text('Tools'),
        Row(
          children: [
            ToolMaker('Score Board', Icon(Icons.score_outlined), ScoreKeeper()),
          ],
        ),
      ],
    );
  }
}

class ToolMaker extends StatelessWidget {
  @required
  final String label;
  @required
  final Icon icon;
  final Navigator link;

  const ToolMaker(this.label, this.icon, this.link);

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => this.link,
                ),
              );
            },
            child: Container(
              height: MediaQuery.of(context).size.width / 4,
              width: MediaQuery.of(context).size.width / 4,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(8)),
                color: Colors.white,
                border: Border.all(color: Colors.grey),
              ),
              child: Center(
                child: this.icon,
              ),
            ),
          ),
          Text(this.label)
        ],
      ),
    );
  }
}

'''

【问题讨论】:

    标签: flutter flutter-navigation


    【解决方案1】:

    按下时,此代码中的“ToolMaker”应导航到 MaterialPageRoute

    这是一个功能,你有几个选择

    1) 使用函数参数代替final Navigator link; 使用final Function onTap;

    在您的手势检测器 onTap 中调用 oncall 函数

    GestureDetector(
                onTap:widget.onTap,
    
    

    然后在创建小部件时解析参数

     ToolMaker('Score Board', Icon(Icons.score_outlined),myFunction),
    

    提示通过在小部件构造函数周围添加 {} 来使用命名参数

     const ToolMaker({this.label, this.icon, this.link});
    

    2 导航使用

    named routes.

    【讨论】:

      【解决方案2】:

      您应该将类​​型 Navigator 更改为 Widget

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-21
        • 2021-04-24
        • 2020-04-21
        • 2020-12-17
        • 2021-10-17
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        相关资源
        最近更新 更多