трепетание, добавление PageRouteBuilder - PullRequest
0 голосов
/ 04 июля 2018

Я пытаюсь изменить свой код перехода для использования PageRouteBuilder. Смотрите метод _gotoThirdPage ().
Проблема в том, что я не могу передать параметры на новую страницу. Например, у меня сбой при передаче заголовка. Также ищем примеры отправки нескольких параметров, например карты. ЗАПРОС: Может ли кто-нибудь изменить метод _gotoThirdPage () для отправки параметров в Class SecondPage. // ====================. Код ниже ===================

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>[

            new RaisedButton(
              onPressed: _gotoSecondPage,
              child: new Text("Goto SecondPage- Normal"),
            ),

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

1 Ответ

0 голосов
/ 04 июля 2018

Я не совсем уверен, что вы пытаетесь сделать. Самый простой способ передать параметры на новую страницу для меня - это использовать конструктор новой страницы, если мне нужно выполнить некоторую обработку - показать / использовать / передать их позже. Хотя я не думаю, что это уместно, если у вас есть большое количество параметров.

Так что в некоторых случаях я бы использовал SharedPrefences . Я думаю, что это будет лучше для отправки нескольких параметров, таких как карта .

Кстати о вашей навигации, я советую вам использовать навигацию с именованными маршрутами. Что-то вроде:

MaterialApp(
  // Start the app with the "/" named route. In our case, the app will start
  // on the FirstScreen Widget
  initialRoute: '/',
  routes: {
    // When we navigate to the "/" route, build the FirstScreen Widget
    '/': (context) => FirstScreen(),
    // When we navigate to the "/second" route, build the SecondScreen Widget
    '/second': (context) => SecondScreen(),
  },
);

А потом:

Navigator.pushNamed(context, '/second');

Документация .

...