简体   繁体   中英

Flutter: Sending variable from one page to another by calling STF widget

I am trying to create a flexible navigation system, that uses one page to display different things pulled from a database. For example If I would click the button Cars it would navigate to the fixed page (Lets call it display page) And it would pull the title and description from the database and show accordingly. So by clicking Cars, it would send the String Cars with it, so i could use it to find the desired thing from the database.

My question is, how can I send this info to the next page? I want to use

ElevatedButton(
          child: Text("Cars"),
          onPressed: (){
            Navigator.push(context, MaterialPageRoute(builder: (context) => HabitPage()));
          },

And send the desired item with HabitPage('cars(for example)') (I have studied C and that's how you would send variables, not sure it will work in dart.)

This is my HabitPage

    class HabitPage extends StatefulWidget {
  @override
  _HabitPageState createState() => _HabitPageState();
}
class _HabitPageState extends State<HabitPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar
      (
          title: new Text("HabitPage")
      ),
      body: new Center(
        child: new Text("HabitPage"),
      ),
    );
  }
}
ElevatedButton(
          child: Text("Cars"),
          onPressed: (){
            Navigator.push(context, MaterialPageRoute(builder: (context) => HabitPage(info: 'Cars'))); // Passing the info as argument
          },


  
  
class HabitPage extends StatefulWidget {
  
  HabitPage({this.info}) : super(key: key);
    
    final String info; // Variable to receive the info as argument
  
  @override
  _HabitPageState createState() => _HabitPageState();
}
  
class _HabitPageState extends State<HabitPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar
      (
          title: new Text("HabitPage ${widget.info}")// Showing the info passed as argument
      ),
      body: new Center(
        child: new Text("HabitPage"),
      ),
    );
  }
}

Make this changes in your code. In the future, you will probably use Named Routes, so you will need this tutorial. https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments#1-define-the-arguments-you-need-to-pass But for now, this is the solution

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