Flutter - Push and Get value between routes

2019-03-25 13:29发布

问题:

How do I send the green string from the HomePage page to the ContaPage page?

I think it's so Navigator.of(context).pushNamed('/conta/green'); but I do not know how to get in the page conta the green string

So, by getting the value of the string I can for example change the color of the backgroundColor of appBar in ContaPage.

main.dart

import "package:flutter/material.dart";

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "MyApp",
      home: new HomePage(),
      routes: <String, WidgetBuilder> {
        '/home': (BuildContext context) => new HomePage(),
        '/conta': (BuildContext context) => new ContaPage()
      },
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ),
    body: new ListView  (
      children: <Widget>[
        new FlatButton(
          child: new Text("ok"),
          textColor: new Color(0xFF66BB6A),               
          onPressed: () {
            Navigator.of(context).pushNamed('/conta');
          },
        ),
      ],
    )
  );
}

class ContaPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ), 
  );
}

回答1:

You can create a MaterialPageRoute on demand and pass the argument to the ContaPage constructor.

import "package:flutter/material.dart";

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "MyApp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ),
    body: new ListView  (
      children: <Widget>[
        new FlatButton(
          child: new Text("ok"),
          textColor: new Color(0xFF66BB6A),
          onPressed: () {
            Navigator.push(context, new MaterialPageRoute(
              builder: (BuildContext context) => new ContaPage(new Color(0xFF66BB6A)),
            ));
          },
        ),
      ],
    )
  );
}

class ContaPage extends StatelessWidget {
  ContaPage(this.color);
  final Color color;
  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: color,
    ),
  );
}


回答2:

You could always make a static variable String with green as it's value in your HomePage and use that value in your routes when you are creating a new ContaPage. Something like this:

import "package:flutter/material.dart";

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "MyApp",
      home: new HomePage(),
      routes: <String, WidgetBuilder> {
        '/home': (BuildContext context) => new HomePage(),
        '/conta': (BuildContext context) => new ContaPage(HomePage.color)
      },
    );
  }
}

class HomePage extends StatelessWidget {

  static String color = "green";

  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ),
    body: new ListView  (
      children: <Widget>[
        new FlatButton(
          child: new Text("ok"),
          textColor: new Color(0xFF66BB6A),               
          onPressed: () {
            Navigator.of(context).pushNamed('/conta');
          },
        ),
      ],
    )
  );
}

class ContaPage extends StatelessWidget {

  ContaPage({this.color})
  String color;

  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ), 
  );
}

There is probably better solutions but this popped into my head first :)



回答3:

It is a bit late, but it might help some one. I think the best way is to use flutter route project fluro.

define some where globally:

final router = Router();

after that define the routes

var contaHandler = Handler(handlerFunc: (BuildContext context, Map<String, dynamic> params) {
  return ContaPage(color: params["color"][0]);
});

void defineRoutes(Router router) {
  router.define("/conta/:color", handler: contaHandler);
}

set the onGenerateRoute in MaterialApp to use the router generator:

 new MaterialApp (
   ...
   nGenerateRoute: router.generator
   ...
 ),

you have to add the fluro in the dependencies :

 dependencies:
     fluro: "^1.3.4"

and do the package upgrade by the following or the IDE way.

 flutter packages upgrade


回答4:

A better solution is already given on Flutter website, how to use:

Arguments

class ScreenArguments {
  final String title;
  final String message;

  ScreenArguments(this.title, this.message);
}

Extract arguments

class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';

  @override
  Widget build(BuildContext context) {
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;
    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}

Register Route

MaterialApp(
  //...
  routes: {
    ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
    //...
  },     
);

Navigate

Navigator.pushNamed(
      context,
      ExtractArgumentsScreen.routeName,
      arguments: ScreenArguments(
        'Extract Arguments Screen',
        'This message is extracted in the build method.',
      ),
    );

Code copied from link.



标签: dart flutter