21

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

5 Answers 5

25

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
  • 1
    Is the process the same if it is popAndPushNamed?
    – rafaelcb21
    Commented Jun 23, 2017 at 20:49
  • 1
    Just call Navigator.pop(context) and then Navigator.push(context, ...). It does the same thing. Commented Jun 23, 2017 at 20:50
7

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.

1
  • 1
    This is the only solution it worked for me. The examples I saw in the flutter page involved the use of onGeneratedRoute, but that event was never called in my case when pushing the named route.
    – Nicolas
    Commented Mar 29, 2019 at 11:19
6

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 :)

4
  • But if I have 3 FlatButton each one sends a color, how do I step each color specified by the push?
    – rafaelcb21
    Commented Jun 23, 2017 at 20:40
  • The onPressed method would look like this: onPressed: () { color = "myNewColor" Navigator.of(context).pushNamed('/conta'); }, Commented Jun 23, 2017 at 20:41
  • You simply change the color in the onPressed function before you navigate. Commented Jun 23, 2017 at 20:43
  • 1
    Surely you can't change the color as its static?
    – Agreensh
    Commented Feb 1, 2018 at 10:45
2

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
3
  • What if I'm having json Object then how can I send ?? I'm trying this navigateTo(context, '/detail_screen/$propertyObj', transition: TransitionType.native); but having no luck. Its giving error on NextScreen. Commented Sep 4, 2018 at 7:40
  • @AnujSharma, try json.encode and json.decode. Actually what I mean is to send the json as a string.
    – karianpour
    Commented Sep 16, 2018 at 12:38
  • @AnujSharma you can try stackoverflow.com/a/55325051/7784230 if it is not solved yet. Commented Apr 18, 2019 at 5:17
2

Passing data from 1st Page to 2nd

In 1st page

// sending "Foo" from 1st page
Navigator.push(context, MaterialPageRoute(builder: (_) => Page2("Foo")));

In 2nd page.

class Page2 extends StatelessWidget {
  final String string;
  Page2(this.string); // receiving "Foo" in 2nd
}

Passing data back from 2nd Page back to 1st

In 2nd page

// sending "Bar" from 2nd
Navigator.pop(context, "Bar");

In 1st page, it is the same which was used earlier but with little modification.

// receiving "Bar" in 1st
String received = await Navigator.push(context, MaterialPageRoute(builder: (_) => Page2("Foo")));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.