flutter 错误:位置参数太多:允许1个,但找到2个

yx2lnoni  于 2022-12-24  发布在  Flutter
关注(0)|答案(3)|浏览(542)

我正在开发一个flutter应用程序,该应用程序从API获取JSON,然后我解析JSON并构建一个列表磁贴,当我尝试运行代码时,我收到此错误。

lib/screens/screen4.dart:112:23: Error: Too many positional arguments: 1 allowed, but 2 found.
Try removing the extra positional arguments.
          return _tile(data[index].ssid,data[index].auth,icon: Icons.wifi);

这是我的代码:

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

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(data[index].ssid, 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');
        },

        //Navigator.pushNamed(context, '/fifth'),

        // => print('on tap'),
        //TO DO: Pass the arguments selected to the next screen, and insert it into the URI
        //TO DO:Hex to ASCII.
      );
}

我的目的是构造ListTile,然后从每个Tile导航到另一个屏幕,有人能帮我检查一下这个代码有什么问题吗?

alen0pnh

alen0pnh1#

您传递的位置参数太多。如果参数在大括号中声明,如titlesubtitle,则在调用方法时必须使用其名称。您也没有传递BuildContext,它是唯一一个没有在大括号中声明的参数。
将其更改为:

return _tile(
    context, 
    title: data[index].ssid,
    subtitle: data[index].auth,
    icon: Icons.wifi
);
gkn4icbw

gkn4icbw2#

您正在使用一个位置参数和4个必需的名称参数。

tTile _tile(BuildContext context,
          {required String title,
          required String subtitle,
          required IconData icon}) =>

您需要传递如下数据

return _tile(
        context,
        subtitle:data[index].ssid,
        title: data[index].auth,
        icon: Icons.wifi,
      );

有关使用using-constructor的详细信息

rt4zxlrg

rt4zxlrg3#

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


void main() {
  runApp(
    const 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) =>  Job.fromJson(job)).toList();
    } else {
      throw Exception('Failed to load jobs from API');
    }
  }



  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: 
      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: const EdgeInsets.only(top: 400),
                      child: const CircularProgressIndicator(
                        backgroundColor: Colors.grey,
                        color: Colors.black,
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }


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

  ListTile _tile(BuildContext context,  String title, String subtitle, IconData icon) =>
      ListTile(
        title: Text(title,
            style: const TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 20,
            )),
        subtitle: Text(subtitle),
        leading: Icon(
          icon,
          color: Colors.grey[500],
        ),
        trailing: const Icon(
          Icons.arrow_forward_ios,
        ),
        onTap: ()

        {
          Navigator.pushNamed(context, '/fifth');
        },





        //Navigator.pushNamed(context, '/fifth'),

        // => print('on tap'),
        //TO DO: Pass the arguments selected to the next screen, and insert it into the URI
        //TO DO:Hex to ASCII.
      );
}

现在应该能用了

相关问题