Flutter,将参数传递给PageRoutebuilder

时间:2018-07-04 14:23:22

标签: flutter flutter-animation

在方法gotoThirdScreen()中,我试图将参数传递给类。 我认为问题始于:     // ================================================ =========     // ===请在此处放置PageRouteBuilderCode。 第二页类具有... widget.title。但不确定如何从_gotoThirdPage()中传递标题。 此代码有效

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

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() {
  }
}

2 个答案:

答案 0 :(得分:2)

您可以在示例中使用onGenerateRoute

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),
      ),
    );
  }
}

答案 1 :(得分:1)

title值传递给SecondPage构造函数:

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);
    },