Home > OS >  Flutter how to open page with arguments
Flutter how to open page with arguments

Time:09-23

I am using this code to open a page with arguments:

_modalBottomSheetMenu() {
    wsModalBottom(
      context,
      title: trans(context, "Categories"),
      bodyWidget: ListView.separated(
        itemCount: _categories.length,
        separatorBuilder: (cxt, i) => Divider(),
        itemBuilder: (BuildContext context, int index) => ListTile(
          title: Text(parseHtmlString(_categories[index].name)),
          onTap: () {
            Navigator.pop(context);
            Navigator.pushNamed(context, "/browse-category",
                    arguments: _categories[index])
                .then((value) => setState(() {}));
          },
        ),
      ),
    );
  }

But now I just want to set arguments directly on the page. I have tried this but it doesn’t work:

BrowseCategoryPage(key: 1),

I got this code in the browsecategorypage:

BrowseCategoryPage({Key key}) : super(key: key);

What can I do to fix this?

CodePudding user response:

An integer cannot be assigned to a Key. Therefore you will get the error message The argument type 'int' can't be assigned to the parameter type 'Key?' (or something similar) when you write BrowseCategoryPage(key: 1).

The Key is (usually) optional. You don't need it and can just create the instance of your widget like so: BrowseCategoryPage()

If you wish to use a Key, then utilize a GlobalKey. Something like:

var _browseKey = GlobalKey();

BrowseCategoryPage(key: _browseKey);

CodePudding user response:

I think a good way will be to use get package for easiness.

First Way -

Get.to(Second(), arguments: ["First", "Second"]);

Then you can receive the data in the Second() screen like this,

var data = Get.arguments;

NOTE: data will be an array here, as we have passed an array in the arguments. So, to get the first argument, you can use data[0] and to get the second argument, you can use data[1].

Second Way - Just make another class model for the arguments, like this,

class SecondScreenModel{

final String first,second;

SecondScreenModel({this.first,this.second});
}

Then do something like this,

Get.to(Second(),arguments: SecondScreenModel(first: "aaa",second:"bbb"));

Receive data in the second screen,

SecondScreenModel model = Get.arguments;
  • Related