Da Ro
Da Ro

Reputation: 75

Flutter pass value of counter to another page

Hello guys i want to pass the data of a counter to a new screen in flutter. I already tried to put the data in the constructor but it wont work. This is the code:

  int _counterb = 0;
setState(() {
        Navigator.of(context).push(
            MaterialPageRoute(builder:
            (BuildContext context) =>
              Draw(_counterb: _counterb),
            ),
        );
      });

So how can I pass this data of _counterb to the second page?

EDIT

I solved the problem. But now I run into another one. I want to pass 12 values. But it only takes two. How can I pass more than 2 positional arguments?

Upvotes: 0

Views: 1023

Answers (2)

Mustafa Bhatkar
Mustafa Bhatkar

Reputation: 355

Did you try accessing your _counterb variable on the Draw page?

I am assuming Draw is StatefulWidget

class Draw extends StatefulWidget {
  final int counter1, counter2, counter3; //Declare any number of variables you want
  const Draw({this.counter1, this.counter2, this.counter3});

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

class DrawState extends State<Draw> {
  @override
  Widget build(BuildContext context) {
    return Text("${widget.counter1} ${widget.counter2} ${widget.counter3}");
  }
}

Your Navigator will look like this

 Navigator.of(context).push(
            MaterialPageRoute(builder:
            (BuildContext context) =>
              Draw(counter1: _counter1, counter2: _counter2, counter3: _counter3),
            ),
        );

Upvotes: 0

Abdulrahman
Abdulrahman

Reputation: 121

I recommend using provider or getx to manage the state in the app instead of passing 12 arguments to different screens;

if you still want to do so, you can send the data to the second screen through settings

for example:

   Navigator.of(context).push(
            MaterialPageRoute(builder:
            (BuildContext context) =>
              Draw(),
              settings: RouteSettings(arguments: {'counterb': _counterb,},),
            ),
        );

and accessing it in the Draw() screen through:

 @override
  void didChangeDependencies() {
    final routeArg =
        ModalRoute.of(context)!.settings.arguments as Map<dynamic, dynamic>;
    final counterb = routeArg['counterb'];
}

also setState() is not needed here

Upvotes: 0

Related Questions