user16867349
user16867349

Reputation:

How do we transfer data from one screen to another screen in flutter?

@override
  Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    title: Text(
      'Category',
    ),
  ),
  body: Center(
    child: FutureBuilder(
      future: fetchCategory(),
      builder: (ctx, snapShot) {
        if (snapShot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        } else {
          return ListView.builder(
            itemCount: snapShot.data["table"].length,
            itemBuilder: (context, index) {
              return ListTile(
                title: TextButton(
                  style: TextButton.styleFrom(
                    textStyle: TextStyle(fontSize: 20),
                  ),
                  onPressed: () {
                    Navigator.pushNamed(context, '/second');
                  },
                  child: Text(snapShot.data["table"][index]["name"]),
                ),
                //subtitle: Text("price: ${snapShot.data["table"][index]["price"]}"),
               );
             },
           );
         }
       },
     ),
   ),
 );
 }

I want to transfer this data (snapShot.data["table"][index]["id"]) and use it to display the results on a second screen / data return String / I want to use the data to display the items that have the same number on the second page, how can I do that

Upvotes: 0

Views: 247

Answers (2)

Jahidul Islam
Jahidul Islam

Reputation: 12595

you can pass data using argument

onPressed: () {
                    Navigator.pushNamed(context, '/second', arguments: snapShot.data["table"][index]);
                  },

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63799

While you are using pushNamed(context, '/second'); and if receiver widget, don't have Constructor to get data, you can pass through ModalRoute like

Navigator.of(context).push(
                  MaterialPageRoute(
                      builder: (context) => WidgetA(),
                      settings: RouteSettings(
                        arguments: "id",
                      )),
                );

and received on second screen as

class WidgetA extends StatelessWidget {
  static final routeName = "/widgetA";
  @override
  Widget build(BuildContext context) {
    final data = ModalRoute.of(context)!.settings;

    late String retriveString;

    if (data.arguments == null)
      retriveString = "empty";
    else
      retriveString = data.arguments as String;

    return Scaffold(
      body: Column(
        children: [
          Text("Widget A"),
          Text("Got data from parent $retriveString"),
        ],
      ),
    );
  }
}

I will suggest you to visit this where I've described different ways passing data.

Upvotes: 1

Related Questions