Flutter, passing parameters to PageRoutebuilder

后端 未结 2 1850
情书的邮戳
情书的邮戳 2021-01-28 06:04

In Method gotoThirdScreen(), I am tryiing to pass parameters to a class. I believe the issue starts at: //========================================================= //===

2条回答
  •  借酒劲吻你
    2021-01-28 06:44

    you can use onGenerateRoute here the example

    main.dart

    void main() {
      runApp(new App());
    }
    

    app.dart

    class App extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
            home: new HomeScreen(),
            routes: {
              '/home': (BuildContext context) => new HomeScreen(),
              //other routes
            },
            //onGenerateRoute Custom
            onGenerateRoute: getGenerateRoute);
      }
    }
    
    Route getGenerateRoute(RouteSettings settings) {
      final List path = settings.name.split('/');
      if (path[0] != '') return null;
    
      if (path[1].startsWith('team')) {
        if (path.length != 3) return null;
        String _title = path[2];
        return new MaterialPageRoute(
          settings: settings,
          builder: (BuildContext context) => new TeamScreen(
                title: _title,
              ),
        );
      }
      // The other paths we support are in the routes table.
      return null;
    }
    

    home_screen.dart

    import 'package:flutter/material.dart';
    
    class HomeScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Home Screen'),
          ),
          body: new Center(
            child: new Column(
              children: [
                new RaisedButton(
                  onPressed: () {
                    String _title = "Team 1";
                    Navigator.pushNamed(context, '/team/$_title');
                  },
                  child: new Text('Go Team 1'),
                ),
                new RaisedButton(
                  onPressed: () {
                    String _title = "Team 2";
                    Navigator.pushNamed(context, '/team/$_title');
                  },
                  child: new Text('Go Team 2'),
                )
              ],
            ),
          ),
        );
      }
    }
    

    team.dart

    import 'package:flutter/material.dart';
    
    class TeamScreen extends StatelessWidget {
      final String title;
    
      const TeamScreen({Key key, this.title}) : super(key: key);
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Team screen'),
          ),
          body: new Center(
            child: new Text(title),
          ),
        );
      }
    }
    

提交回复
热议问题