简体   繁体   English

Flutter Navigator.of(context).pushNamed 没有将参数传递到下一个屏幕

[英]Flutter Navigator.of(context).pushNamed not passing the argument to the next screen

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:我的 List Tile 屏幕有以下问题,当你 select 特定的 Tile 它应该将 arguments 传递到下一个屏幕时,我不知道缺少什么,但导航器没有传递 arguments 并且它没有报告任何错误要么。这是代码:

Screen 4:屏幕 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:屏幕 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.我在两个屏幕上都设置了一些打印件,以确认没有将任何内容传递到下一个屏幕。

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);

You can try changing this line您可以尝试更改此行

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

to

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

or要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter:如何将 PageRoute Animation 与 Navigator.of(context).pushNamed 结合起来 - Flutter: How to combine PageRoute Animation with Navigator.of(context).pushNamed Flutter: Navigator.of(context).pop() 返回黑屏 - Flutter: Navigator.of(context).pop() return black screen 如何使用 Navigator.of(context).pushNamed 显示 function showModalBottomSheet 或 showDialog? - How to use Navigator.of(context).pushNamed to show function showModalBottomSheet or showDialog? Flutter Navigator.pushNamed() 上下文 - Flutter Navigator.pushNamed() context 颤振:异常使用 Navigator.of(context).pop(); - Flutter: Exception using Navigator.of(context).pop(); 调用 Navigator.of(context, rootNavigator: true).pop() 会出现黑屏 - Calling Navigator.of(context, rootNavigator: true).pop() gives black screen Flutter-Alternative of Navigator.of(context).pop(true); - Flutter-Alternative of Navigator.of(context).pop(true); Flutter Navigator.of(context).pop() in showDialog,关闭 ios 中的完整应用程序 - Flutter Navigator.of(context).pop() in showDialog, close full app in ios Navigator.of(context).pop(); 使整个屏幕消失,而不是弹出 - Navigator.of(context).pop(); makes the whole screen disappear, not the popup Navigator.of(context,).pop()时中间黑屏 - Intermediate black screen when Navigator.of(context,).pop()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM