Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass arguments from Modal Route to a post http request in Flutter

I’m passing arguments with pushNamed to a screen and I can access it inside my ListView but then I want to send some of the arguments with an ElevatedButton to my post request but I can’t access it. I’ve tried many ways to do this can someone tell me what I’m doing wrong? Thanks in advance!

Where I use pushNamed

 child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                    disabledBackgroundColor: Colors.grey),
                onPressed: (() async {
                        Navigator.of(context).pushNamed(
                            SelectedAthletes.routeName,
                            arguments: selectedAthlete.toList());
                      })

The screen I’m passing the argument

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class SelectedAthletes extends StatefulWidget {
  const SelectedAthletes({Key? key}) : super(key: key);

  static const routeName = '/selectedAthletes';

  @override
  State<SelectedAthletes> createState() => _SelectedAthletesState();
}

class _SelectedAthletesState extends State<SelectedAthletes> {
  @override
  Widget build(BuildContext context) {
     final args = ModalRoute.of(context)!.settings.arguments as List<Athlete>;
    return Scaffold(
        backgroundColor: const Color(0Xfff7f7f5),
        body: Stack(
          children: [
            SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ListView.builder(
                    shrinkWrap: true,
                    cacheExtent: 34,
                    primary: true,
                    physics: const ClampingScrollPhysics(),
                    padding: const EdgeInsets.only(
                      top: 10,
                      bottom: 56,
                    ),
                    itemCount: args.length,
                    itemBuilder: (BuildContext context, int index) {
                      return ListTile(
                          leading: const Icon(Icons.history_outlined,
                              color: Colors.black, size: 25),
                          title: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Text(
                                    'ID: ${args[index].id}',
                                    style: const TextStyle(
                                        color: Colors.blue, fontSize: 14),
                                  ),
                                  const SizedBox(
                                    width: 5,
                                  ),
                              Row(
                                children: [
                                  Flexible(
                                    child: Text(
                                      '${args[index].lastName} ${args[index].firstName}',
                                      style: const TextStyle(
                                          color: Colors.black,
                                          fontFamily: 'Cera',
                                          fontWeight: FontWeight.bold,
                                          fontSize: 18),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 5,
                              ),
                              Row(
                                children: [
                                  Text(
                                    '(${args[index].fatherName})',
                                    style: const TextStyle(
                                        color: Colors.black,
                                        fontFamily: 'Cera',
                                        fontSize: 14),
                                  ),
                                  const SizedBox(
                                    width: 20,
                                  ),
                                  Text(
                                    'Π: ${args[index].currentMonthPresences}',
                                    style: const TextStyle(
                                        color: Colors.black,
                                        fontFamily: 'Cera',
                                        fontSize: 14),
                                  ),
                                  const SizedBox(
                                    width: 50,
                                  ),
                                ],
                              ),
                            ],
                          ));
                    },
                  )
                ],
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                width: double.infinity,
                height: 60,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      disabledBackgroundColor: Colors.grey),
                  onPressed: () async {
                    await ApiService.insertPresences(args[index].id, args[index].firstName, args[index].lastName);
                  },
                  child: const Center(
                    child: Text(
                      'SEND',
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                          fontSize: 18),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ));
  }

My post request

static Future<Athlete> insertPresences(
      int athleteId, int departmentId, int teamId) async {
    try {
      final response = await http.post(
          Uri.parse(
              'http://164.92.170.94:8080/nox/api/nox/api/insert-presences'),
          headers: {
            'Authorization': 'Basic a2F4cmlzOjEyMzQ1',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: jsonEncode(<String, int>{
            "athleteId": athleteId,
            "departmentId": departmentId,
            "teamId": teamId,
          }));
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');
      if (response.statusCode == 201) {
        return Athlete.fromJson(jsonDecode(response.body));
      }
    } catch (e) {
      logger.e(e.toString());
    }
    return insertPresences(athleteId, departmentId, teamId);
  }

Error in my ElevatedButton in SelectedAthletes screen

Undefined name 'index'.
Try correcting the name to one that is defined, or defining the name.

>Solution :

You passed a List to your second screen and you need to specify which item you want to pass to your api.

If you want pass the first item, simply use 0 instead of index like this:

          onPressed: () async {
            await ApiService.insertPresences(args[0].id, args[0].firstName, args[0].lastName);
          },

And if you want to show a button for all items, you need to move the ElevatedButton widget to your ListView.builder widget like this:

ListView.builder(
  ...,
  itemBuilder: (BuildContext context, int index) {
  //You can use index here
    return ListTile(
    ...,
    title: Column(
      children: [
      ...,//some other widgets
        ElevatedButton(
        ...,
          onPressed: () async {
            await ApiService.insertPresences(args[index].id, args[index].firstName, args[index].lastName);
          },
      ]
    );
  }
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading