如何传递参数到路由?

时间:2019-07-18 21:02:53

标签: flutter

我尝试将参数“ _difficulty”从“第一页”传递给“第二页”,但是我不知道该怎么做: 此参数是一个字符串,表示难度模式(简单,正常,困难)

首页: 当用户单击按钮时,称为OnPressed

onPressed: () {
   Navigator.pushNamed(context, '/gamepage', arguments: _difficulty);
},

第二页 该调用接收参数以显示值

 import 'package:flutter/material.dart';

 class GamePage extends StatelessWidget {    
  final String difficultyMode;
  GamePage(this.difficultyMode);

  @override
  Widget build(BuildContext context) {

    final GamePage args = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      body:  new Container(
          child: SingleChildScrollView(
              child: Text(args.difficultyMode)
          )
      ),
    );
  }
}

在main.dart中: 我使用onGenerateRoute:_getRoute,

Route _getRoute(RouteSettings settings) {
    switch (settings.name){
      case '/':
        return _buildRoute(settings, new Homepage());
      case '/credits':
        return _buildRoute(settings, new Credits());
      case '/gamepage':
        return _buildRoute(settings, new GamePage(diffculty));
      default:
        return null;
    }
  }

1 个答案:

答案 0 :(得分:1)

您可以通过RouteSettings获得论点。

您可以按以下方式访问它:

case '/gamepage':
    String difficulty = settings.arguments;
    return _buildRoute(settings, new GamePage(difficulty));

希望有帮助!