Alex Ali
Alex Ali

Reputation: 1369

Passing 2 Variables from 2 Diffreent Screen to 1 Screen

I have Home() , Category(), Region() classes

To add category I navigate to Category() and to add region I navigate to Region()

I want pass the values of cat inside Category and the value of city inside Region to Home screen, but I receive this error:

Compiler message:
lib/Screens/regions.dart:32:95: Error: Too few positional arguments: 2 required, 1 given.
                Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>Home(city)));

Here is Home Screen:

 class Home extends StatefulWidget {

  final String sRegion;
  final String sCategory;

  Home(this.sRegion,this.sCategory, {Key key}):super(key: key);
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
 @override
  Widget build(BuildContext context) {
return Directionality(
  textDirection: TextDirection.rtl,
  child: Scaffold(
    body: Center(
      child: Text(cat + city),
    ),
  ),
);
  }
}

Category Screen:

 class Category extends StatefulWidget {

  @override
  _CategoryState createState() => _CategoryState();
}

class _CategoryState extends State<Category> {
 @override
  Widget build(BuildContext context) {
 String cat = 'General';
return Directionality(
  textDirection: TextDirection.rtl,
  child: Scaffold(
    body: Center(
      child: FlatButton( onPressed: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>Home(cat)));
          },),
    ),
  ),
);
  }
}

Region Screen:

     class Region extends StatefulWidget {

  @override
  _RegionState createState() => _RegionState();
}

class _RegionState extends State<Region> {
 @override
  Widget build(BuildContext context) {
 String city = 'London';
return Directionality(
  textDirection: TextDirection.rtl,
  child: Scaffold(
    body: Center(
      child: FlatButton( onPressed: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>Home(city)));
          },),
    ),
  ),
);
  }
}

Upvotes: 0

Views: 32

Answers (1)

Claudio Redi
Claudio Redi

Reputation: 68400

Home has two positional parameters that are mandatory (sRegion and sCategory). Those are not optional and you have to provide them.

Navigator.pushReplacement(context, 
     MaterialPageRoute(builder: (context)=>Home(city, cat)));

Notice that I added cat to Home constructor. If any of those parameters is optional you need to rewrite the constructor signature.

If you want to make any of those parameters optional, convert them to named arguments

Home({this.sRegion,this.sCategory, Key key}):super(key: key);

Upvotes: 1

Related Questions