Home > other >  Flutter Navigator.of(context).pushNamed not passing the argument to the next screen
Flutter Navigator.of(context).pushNamed not passing the argument to the next screen

Time:12-29

I have the following problem with a List Tile screen, when you select the specific Tile it should pass the arguments to the next screen, I don't know what is missing, but the navigator is not passing the arguments and it is not reporting any error either.Here is the code:

Screen 4:

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:australremote/screens/screen5.dart';



void main() {
  runApp(
      JobsListView(),
  );
}

class Job {
  final String ssid;
  final String auth;
  final String encry;

  Job({required this.ssid, required this.auth,required this.encry});

  factory Job.fromJson(Map<String, dynamic> json) {
    return Job(
      ssid: json['ssid'],
      auth: json['auth'],
      encry: json['encry'],
    );
  }
}

class JobsListView extends StatelessWidget {
  const JobsListView({Key? key}) : super(key: key);


  Future<List<Job>> _fetchJobs() async {
    final response = await http
        .get(
        Uri.parse('http://10.10.10.254/httpapi.asp?command=wlanGetApListEx'));

    if (response.statusCode == 200) {
      final List jsonResponse = json.decode(response.body)['aplist'] as List;
      return jsonResponse.map((job) => new Job.fromJson(job)).toList();
    } else {
      throw Exception('Failed to load jobs from API');
    }
  }





  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Finding your available networks',
            style: TextStyle(color: Colors.black87)),

        titleSpacing: 00.0,
        centerTitle: true,
        toolbarHeight: 60.2,
        toolbarOpacity: 0.6,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              bottomRight: Radius.circular(25),
              bottomLeft: Radius.circular(25)),
        ),
        elevation: 0.00,
        backgroundColor: Colors.transparent,


      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: FutureBuilder<List<Job>>(
                future: _fetchJobs(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<Job> data = snapshot.data ?? [];
                    return _jobsListView(data);
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}");
                  }
                  return Container(
                    alignment: Alignment.topCenter,
                    margin: EdgeInsets.only(top: 400),
                    child: CircularProgressIndicator(
                      backgroundColor: Colors.grey,
                      color: Colors.black,
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }



  ListView _jobsListView(data) {
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return _tile(
              context,
              title: data[index].ssid,
              subtitle: data[index].auth,
              icon: Icons.wifi
          );
        });
  }


    ListTile _tile(BuildContext context, {required String title,required String subtitle,required IconData icon}) =>
        ListTile(
          title: Text(title,
              style: TextStyle(
                fontWeight: FontWeight.w500,
                fontSize: 20,
              )),
          subtitle: Text(subtitle),
          leading: Icon(
            icon,
            color: Colors.grey[500],
          ),
          trailing: Icon(
            Icons.arrow_forward_ios,
          ),
          onTap: ()
          {
            //Navigator.pushNamed(context, '/fifth');
            print(title);
            print(subtitle);

            Navigator.of(context).pushNamed(
              '/fifth',
              arguments:[title,subtitle],
            );
            },


          //TO DO: Pass the arguments selected to the next screen, and insert it into the URI
          //TO DO:Hex to ASCII.
        );
  }








Screen 5:



import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:australremote/screens/screen4.dart';

void main() {
  runApp(MyHomePage());
}


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



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

class _MyHomePageState extends State<MyHomePage> {
  final _textController = TextEditingController();

  final String? title = '';
  final String? subtitle = '';
  final String? encry= '';


  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)?.settings?.arguments;
    print(title);
    print(subtitle);
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Home wifi network:$title, Authentication: $subtitle'),

            TextField(
              controller: _textController,
              decoration: InputDecoration(hintText: "Enter the password of your Wifi network"),
            ),
            TextButton(
              style: TextButton.styleFrom(
                primary: Colors.blue,
              ),
              onPressed: () async {
                // You can get the entered text using the text controller
                String enteredText = _textController.text;
                // Send the text to the API using the http package
                final response = await http.get(Uri.parse(
                  "http://10.10.10.254/httpapi.asp?command=wlanConnectApEx:ssid=$title:ch=1:auth=$subtitle:encry=:pwd=$enteredText:chext=1"),
                      //"text=$enteredText",
                );
                if (response.statusCode == 200) {

                  Navigator.pushNamed(context, '/');
                } else {
                  // There was an error with the request
                  // You can handle the error here
                }
              },
              child: Text("Connect"),
            ),
          ],
        ),
      ),
    );
  }
}


I set some prints on both screen to confirm that is not passing anything to the next screen.

CodePudding user response:

You are not reading the title and subtitle.

final args = ModalRoute.of(context)?.settings?.arguments;
title = args['title'];
subtitle = args['subtitle'];
print(title);
print(subtitle);

CodePudding user response:

You can try changing this line

final args = ModalRoute.of(context)?.settings?.arguments;

to

final args = ModalRoute.of(context)?.settings?.arguments as List<String>;

or

List<String> args = ModalRoute.of(context)?.settings?.arguments;

Casting like this might solve your problem.

This is like telling Flutter that the arguments you passed is a List.

Then you can access the args like args[0] and args[1].

  • Related