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

Time:10-27

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

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.

CodePudding user response:

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);
          },
      ]
    );
  }
)
  • Related