简体   繁体   中英

Flutter, passing parameters to PageRoutebuilder

In Method gotoThirdScreen(), I am tryiing to pass parameters to a class. I believe the issue starts at: //========================================================= //=== please put PageRouteBuilderCode here. The Class SecondPage has... widget.title. But not sure how to pass titel from _gotoThirdPage(). This code works

//===============================

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),

    // Added  ===
    routes: <String, WidgetBuilder>{
       SecondPage.routeName: (BuildContext context) => new SecondPage(title: "SecondPage"),
     },


    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Padding(
              padding: const EdgeInsets.all(28.0),
              child: new RaisedButton(
                onPressed: _gotoSecondPage,
                child: new Text("Goto SecondPage- Normal"),
              ),
            ),

            Padding(
              padding: const EdgeInsets.all(38.0),
              child: new RaisedButton(
                onPressed: _gotoThirdPage,
              child: new Text("goto SecondPage = with PRB"),
              ),
            ),

            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _gotoSecondPage() {
    //=========================================================
    //  Transition - Normal Platform Specific
    print('====  going to second page ===');
    print( SecondPage.routeName);
    Navigator.pushNamed(context, SecondPage.routeName);
  }

  void _gotoThirdPage() {
    //=========================================================
    //  I believe this is where I would be adding a PageRouteBuilder
    print('====  going to second page ===');
    print( SecondPage.routeName);
    //Navigator.pushNamed(context, SecondPage.routeName);

    //=========================================================
    //===  please put PageRouteBuilderCode here.

    final pageRoute = new PageRouteBuilder(
      pageBuilder: (BuildContext context, Animation animation,
          Animation secondaryAnimation) {
        // YOUR WIDGET CODE HERE
        //  I need to PASS title here...
        // not sure how to do this.
        // Also, is there a way to clean this code up?


      return new SecondPage();
      },
      transitionsBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation, Widget child) {
        return SlideTransition(
          position: new Tween<Offset>(
            begin: const Offset(1.0, 0.0),
            end: Offset.zero,
          ).animate(animation),
          child: new SlideTransition(
            position: new Tween<Offset>(
              begin: Offset.zero,
              end: const Offset(1.0, 0.0),
            ).animate(secondaryAnimation),
            child: child,
          ),
        );
      },
    );
    Navigator.of(context).push(pageRoute);



  }
}


class SecondPage extends StatefulWidget {
  SecondPage({Key key, this.title}) : super(key: key);

  static const String routeName = "/SecondPage";

  final String title;

  @override
  _SecondPageState createState() => new _SecondPageState();
}

/// // 1. After the page has been created, register it with the app routes 
/// routes: <String, WidgetBuilder>{
///   SecondPage.routeName: (BuildContext context) => new SecondPage(title: "SecondPage"),
/// },
///
/// // 2. Then this could be used to navigate to the page.
/// Navigator.pushNamed(context, SecondPage.routeName);
///

class _SecondPageState extends State<SecondPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        //========   HOW TO PASS widget.title ===========
        title: new Text(widget.title),
        //title: new Text('====  second page ==='),
      ),
      body: new Container(),
      floatingActionButton: new FloatingActionButton(
        onPressed: _onFloatingActionButtonPressed,
        tooltip: 'Add',
        child: new Icon(Icons.add),
      ),
    );
  }

  void _onFloatingActionButtonPressed() {
  }
}

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: <String, WidgetBuilder>{
          '/home': (BuildContext context) => new HomeScreen(),
          //other routes
        },
        //onGenerateRoute Custom
        onGenerateRoute: getGenerateRoute);
  }
}

Route<Null> getGenerateRoute(RouteSettings settings) {
  final List<String> 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<Null>(
      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: <Widget>[
            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),
      ),
    );
  }
}

Pass title value to SecondPage constructor:

void _gotoThirdPage() {
  String page_title = "Yet Another Page";

  final pageRoute = new PageRouteBuilder(
    pageBuilder: (BuildContext context, Animation animation,
        Animation secondaryAnimation) {
      return new SecondPage(title: page_title);
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM