Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何在没有空值的情况下将对象列表传递给其他函数_Flutter_Dart - Fatal编程技术网

Flutter 如何在没有空值的情况下将对象列表传递给其他函数

Flutter 如何在没有空值的情况下将对象列表传递给其他函数,flutter,dart,Flutter,Dart,我是Stackoverflow新手,也是Flatter的初学者,我在使用api从internet获取数据时遇到了一个问题,我必须通过get方法从internet获取一些数据,然后将我得到的所有内容都推到PlayerUpdate对象数组中,我在控制台中的getFixtures函数中显示,我可以看到它不是null,我可以看到legth=16和它的id fixtures,在这个函数中,以及在ple数组中必须填充的所有16个元素之后,我调用另一个函数来传递ple数组,然后这个函数将对我发送给Update

我是Stackoverflow新手,也是Flatter的初学者,我在使用api从internet获取数据时遇到了一个问题,我必须通过get方法从internet获取一些数据,然后将我得到的所有内容都推到PlayerUpdate对象数组中,我在控制台中的getFixtures函数中显示,我可以看到它不是null,我可以看到legth=16和它的id fixtures,在这个函数中,以及在ple数组中必须填充的所有16个元素之后,我调用另一个函数来传递ple数组,然后这个函数将对我发送给UpdateRequest函数的数组ple进行post,令我震惊的是,在将ple作为参数传递给update函数后,我可以看到update函数将其视为null,我不明白发生了什么,在通过之前,我将其设置为空,这很好

下面是我在《颤栗》中尝试过的:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:footyappp/Fantazyy/club_edit.dart';
import 'package:footyappp/Fantazyy/club_update.dart';
import 'package:footyappp/Fantazyy/player_update_view.dart';
import 'package:footyappp/Fantazyy/squad_list.dart';
import 'package:footyappp/Fantazyy/styles.dart';
import 'package:footyappp/Fantazyy/player%20copy.dart';
import 'package:footyappp/Key/Key.dart';
import 'package:http/http.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'get_fixtures.dart';
import 'insert_fixture.dart';


class TeamDisplayView extends StatefulWidget {

  List<Playerr> selectedPlayers = [];

  TeamDisplayView({
    Key key,
    players,
    selectedPlayers,
  }) : selectedPlayers = (selectedPlayers == null) ? new List<Playerr>.generate(16, (int index) => null) : selectedPlayers;

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

class _TeamDisplayViewState extends State<TeamDisplayView> {

  List<GetFixtures> results = [];
  String round;
  List<int> fixturesIds = [];
  List<PlayerUpdate> ple = [];
  int fixtureid;



  PostRequest(String rnd) async {

// set up POST request arguments
    final url = Uri.parse('${ApiKey.url}/api/questions/addFixture');
    Map<String, String> headers = {"Content-type": "application/json"};
    List<Fixt> pls = [];

    for(var item in results){
      pls.add( Fixt(id: item.fixture.id,round: rnd)  );
    }

    InsertFixtures insertFx = InsertFixtures(fixt: pls);
    var json = jsonEncode(insertFx.toJson());

    // make POST request
    Response response = await post(url, headers: headers, body: json);
    String res = response.body;

    return response;
  }

  getClubId() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int clubids = prefs.getInt("clubID");
    print(clubids);
    makePostRequest(clubids);

  }

  Future<void> makePostRequest(int clubid) async {
    // set up POST request arguments
    String url = '${ApiKey.url}/api/questions/getclub';
    Map<String, String> headers = {"Content-type": "application/json"};
    String json = '{"clubid": "' + clubid.toString() + '"}';
    Response response = await post(url, headers: headers, body: json);
    String res = response.body;
    Map parsed = jsonDecode(res);
    ClubEdit club = ClubEdit.fromJson(parsed);

    setState(() {
      clubName = club.data.name;
      //budget = club.data.price.toDouble();
      points = club.data.points;
      fixture = club.data.fixture;
    });
    print("clubname" + clubName);
    print("budget" + budget.toString());
    print("points" + points.toString());
    print("fixture" + fixture.toString());
    print(_isLoading);


  }

  Future<void>  getFixtures(int id,int plid,String fn,String ln,String ps,double price,String rating,int app, int goals, int assists, int cshet,int red, int yell,String img, int teamid) async {
    http.Response response = await http.get(
        'https://v3.football.api-sports.io/fixtures?team=$id&league=39&season=2020&last=1',
        headers: {'x-rapidapi-key': ApiKey.key,
          'x-rapidapi-host':'v3.football.api-sports.io'});
    String body = response.body;
    var data = jsonDecode(body);
    List<dynamic> clubList = data['response'];
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      results = clubList
          .map((dynamic item) => GetFixtures.fromJson(item))
          .toList();
      round = results[0].league.round.toString();
      fixtureid = results[0].fixture.id;
      ple.add(PlayerUpdate(
          id: plid,
          firstname: fn,
          lastname: ln,
          position: ps,
          price: price,
          rating: rating,
          appearences: app,
          goals: goals,
          assists: assists,
          cleansheets: cshet,
          redcards: red,
          yellowcards: yell,
          image: img,
          teamid: teamid,
          clubid: clubid,
          fixtureid: fixtureid
      ));
    });
    print("ple length"+ple.length.toString());
    for(var item in ple) {
      print("ple fixture" + item.fixtureid.toString());
    }
            if(ple.length ==16 ){
              updateRequest(
                  userid,
                  "dhya@hotmail.com",
                  20,
                  "22",
                  "password",
                  "name",
                  25.0,
                 this.ple);
            }




    print("round     :"+round);
    prefs.setString("round",round);
//    this.PostRequest(round);
  }

  updateRequest(int userid, String email, int points, String fixtures,
      String password, String name, double price, List<PlayerUpdate> players) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    email = prefs.getString("userEmail");
    password = prefs.getString("userPassword");
    int clubid = prefs.getInt("clubID");
    print(clubid);

    setState(() {
      userid = prefs.getInt("userID");
    });
bool a = false;
for(var item in players){
  if(item == null){
    a = true;
  }
}
    if(a == true){
      Fluttertoast.showToast(
          msg: "Missing Players",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0
      );
    }else{


// set up POST request arguments
    final url = Uri.parse('${ApiKey.url}/api/questions/updateQuestion');
    Map<String, String> headers = {"Content-type": "application/json; charset=utf-8"};

    ClubUpdate club = ClubUpdate(
        userid: clubid,
        email: email,
        password: password,
        name: name,
        price: price,
        players: players);

    var json = jsonEncode(club.toJson());

    print(club.name);
    print(club.price);
    for (var item in club.players) {
      print("ple"+item.price.toString());
    }

    // make POST request
    Response response = await post(url, headers: headers, body: json);
    // check the status code for the result
    int statusCode = response.statusCode;
    // this API passes back the id of the new item added to the body
    String body = response.body;
    print("response body" + response.body);

    Fluttertoast.showToast(
        msg: "Team Updated Successfully",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0
    );
    Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) {return SquadList();}));
    //Navigator.push(context, MaterialPageRoute(builder: (context)=>BodyFantasy(),),);
    }
    //return response;
  }

  int clubid;
  String clubName;
  bool _isLoading = true;
  double budget = 220.0;
  List<Playerr> pl = [];
  int points;
  String fixture;
  String _teamName = "";
  Widget _saveChanges = Text("Press to save changes");
  int userid;
  String email;
  String password;

  @override
  void initState() {
    super.initState();
    this.getClubId();
    for (Playerr player in widget.selectedPlayers) {
      if (player != null) {
          budget -= player.price;
      }

    }
    print("clubname" + clubName.toString());
    print("budget" + budget.toString());
    print("points" + points.toString());
    print("fixture" + fixture.toString());
    print(_isLoading);


  }

  emptyPlayer(int index) {

    Playerr player = widget.selectedPlayers[index];
    Widget playerView;

    if (player == null) {
      playerView = Image.asset(
        "Assets/shirt_blank.png",
        fit: BoxFit.fitHeight,
      );
    } else {
      playerView = Column(
        children: <Widget>[
          Expanded(
            child: Image.asset(
              player.image,
              fit: BoxFit.fitHeight,
            ),
          ),
          Container(
            color: Colors.black,
            child: Text(
              player.firstName.substring(0, 1) + ". " + player.lastName,
              textAlign: TextAlign.center,
              softWrap: false,
              overflow: TextOverflow.fade,
            ),
          ),
          Container(
            color: Colors.black,
            child: Text("£${player.price}m", textAlign: TextAlign.center),
          ),
        ],
      );
    }

    return Expanded(
      child: InkWell(
          onTap: () =>
              Navigator.pushReplacement(context,
                  MaterialPageRoute(builder: (BuildContext context) {
                    return PlayerUpdateView(
                      selectedPlayers: widget.selectedPlayers,
                      playerIndex: index,
                    );
                  })),
          child: Padding(
            padding: EdgeInsets.only(left: 3.0, right: 3.0),
            child: playerView,
          )),
    );

  }

  @override
  Widget build(BuildContext context) {

   return WillPopScope(
            onWillPop: () async => false,
            child: Scaffold(
                appBar: AppBar(
                  title: Text("Your team"),
                ),
                body: Stack(
                  children: <Widget>[
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Expanded(
                            child: Stack(children: <Widget>[
                          Positioned.fill(
                              child: Image.asset(
                            "Assets/pitch.jpg",
                            fit: BoxFit.fitWidth,
                            alignment: Alignment.topLeft,
                          ))
                        ])),
                      ],
                    ),
                    Column(
                      //players
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Expanded(flex: 1, child: Container()),
                        Expanded(
                            flex: 6,
                            child: Padding(
                              padding: EdgeInsets.only(left: 40.0, right: 40.0),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: List.generate(
                                    2, (index) => emptyPlayer(index)),
                              ),
                            )),
                        Expanded(flex: 1, child: Container()),
                        Expanded(
                            flex: 6,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: List.generate(
                                  5, (index) => emptyPlayer(index + 2)),
                            )),
                        Expanded(flex: 1, child: Container()),
                        Expanded(
                            flex: 6,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: List.generate(
                                  5, (index) => emptyPlayer(index + 7)),
                            )),
                        Expanded(flex: 1, child: Container()),
                        Expanded(
                            flex: 6,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: List.generate(
                                  4, (index) => emptyPlayer(index + 12)),
                            )),
                        Expanded(flex: 1, child: Container()),
                        Container(
                          color: Styles.colorAccentDark,
                          padding: EdgeInsets.only(left: 8.0, right: 8.0),
                          child: Column(
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(top: 4.0, bottom: 4.0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Text(
                                        "Team Name",
                                        style: Styles.budgetLabel,
                                      ),
                                    ),
                                    Text(
                                      "${clubName}",
                                      style: Styles.budgetLabel,
                                    )
                                  ],
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 4.0, bottom: 4.0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Text(
                                        "Fixture",
                                        style: Styles.budgetLabel,
                                      ),
                                    ),
                                    Text(
                                      "${fixture}",
                                      style: Styles.budgetLabel,
                                    )
                                  ],
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 4.0, bottom: 4.0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Text(
                                        "Remaining Budget",
                                        style: Styles.budgetLabel,
                                      ),
                                    ),
                                    Text(
                                      "£${budget}m",
                                      style: Styles.budgetLabel,
                                    )
                                  ],
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 4.0, bottom: 4.0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Text(
                                        "Points",
                                        style: Styles.budgetLabel,
                                      ),
                                    ),
                                    Text(
                                      "${points}",
                                      style: Styles.budgetLabel,
                                    )
                                  ],
                                ),
                              ),


                            ],
                          ),
                        ),
                        new MaterialButton(
                            height: 50.0,
                            minWidth: double.infinity,
                            color: Styles.colorButton,
                            splashColor: Colors.teal,
                            textColor: Colors.white,
                            child: _saveChanges,
                            onPressed: () {

                              if (widget.selectedPlayers.length == 16) {
                                for(var item in widget.selectedPlayers){
                                  getFixtures(item.teamid,item.playerID,item.firstName,item.lastName,item.position,item.price,item.rating,item.appearances,item.goals,item.assists,item.cleanSheets,item.redCards,item.yellowCards,item.image,item.teamid);
                                }

                              }
                            }),
                      ],
                    ),
                  ],
                )));
  }
}
导入'dart:convert';
进口“包装:颤振/材料.省道”;
进口“包装:fluttoast/fluttoast.dart”;
导入“包:footyappp/fantazy/club_edit.dart”;
导入“包:footyappp/fantazy/club_update.dart”;
导入“包:footyappp/fantazy/player_update_view.dart”;
导入“package:footyappp/Fantazy/squad_list.dart”;
导入“package:footyappp/fantazy/styles.dart”;
导入“包:footyappp/fantazy/player%20copy.dart”;
导入“包:footyappp/Key/Key.dart”;
导入“包:http/http.dart”;
导入“package:shared_preferences/shared_preferences.dart”;
将“package:http/http.dart”导入为http;
导入“get_fixtures.dart”;
导入“插入夹具.省道”;
类TeamDisplayView扩展了StatefulWidget{
列出所选玩家=[];
TeamDisplayView({
关键点,
球员们,
精选球员,
}):selectedPlayers=(selectedPlayers==null)?新建列表。生成(16,(int索引)=>null):selectedPlayers;
@凌驾
_TeamDisplayViewState createState()=>\u TeamDisplayViewState();
}
类_TeamDisplayViewState扩展状态{
列出结果=[];
串圆;
列表fixturesIds=[];
列表ple=[];
内固定体;
PostRequest(字符串rnd)异步{
//设置请求后参数
final url=Uri.parse('${ApiKey.url}/api/questions/addFixture');
映射头={“内容类型”:“应用程序/json”};
列表pls=[];
对于(结果中的var项){
请添加(固定件(id:item.fixture.id,round:rnd));
}
InsertFixtures insertFx=InsertFixtures(固件:pls);
var json=jsonEncode(insertFx.toJson());
//发帖
Response-Response=wait-post(url,headers:headers,body:json);
String res=response.body;
返回响应;
}
getClubId()异步{
SharedReferences prefs=等待SharedReferences.getInstance();
int clubids=prefs.getInt(“clubID”);
印刷品(俱乐部投标);
makePostRequest(clubids);
}
未来makePostRequest(int-clubid)异步{
//设置请求后参数
字符串url='${ApiKey.url}/api/questions/getclub';
映射头={“内容类型”:“应用程序/json”};
字符串json='{“clubid”:“'+clubid.toString()+'”}”;
Response-Response=wait-post(url,headers:headers,body:json);
String res=response.body;
Map parsed=jsonDecode(res);
ClubEdit club=ClubEdit.fromJson(已解析);
设置状态(){
clubName=club.data.name;
//budget=club.data.price.toDouble();
积分=club.data.points;
fixture=club.data.fixture;
});
打印(“clubname”+clubname);
打印(“budget”+budget.toString());
打印(“points”+points.toString());
打印(“fixture”+fixture.toString());
打印(卸载);
}
未来的getfixture(int-id、int-plid、String-fn、String-ln、String-ps、双倍价格、String-rating、int-app、int-goals、int-assistance、int-cshet、int-red、int-yell、String-img、int-teamid)异步{
http.Response-Response=等待http.get(
'https://v3.football.api-sports.io/fixtures?team=$id和联赛=39和赛季=2020和最后一个=1',
标题:{'x-rapidapi-key':ApiKey.key,
'x-rapidapi-host':'v3.football.api sports.io';
字符串体=response.body;
var数据=jsonDecode(主体);
List clubList=data['response'];
SharedReferences prefs=等待SharedReferences.getInstance();
设置状态(){
结果=俱乐部列表
.map((动态项)=>GetFixtures.fromJson(项))
.toList();
round=结果[0]。league.round.toString();
fixtureid=结果[0]。fixture.id;
示例添加(播放更新)(
id:plid,
名字:fn,,
姓氏:ln,
职位:ps,,
价格:价格,
评级:评级,
外观:应用程序,
目标:目标,
助攻:助攻,
清洁纸:cshet,
红色卡片:红色,
黄色卡片:大叫,
图片:img,
teamid:teamid,
clubid:clubid,
fixtureid:fixtureid
));
});
打印(“ple length”+ple.length.toString());
用于(ple中的var项目){
打印(“ple fixture”+item.fixtureid.toString());
}
如果(长度==16){
更新请求(
用户ID,
"dhya@hotmail.com",
20,
"22",
“密码”,
“姓名”,
25.0,
这个(ple),;
}
打印(“圆形:+圆形);
首选设置字符串(“圆形”,圆形);
//本次申请(轮);
}
updateRequest(int userid、字符串电子邮件、int points、字符串fixture、,
字符串密码、字符串名称、双倍价格、列表播放器)异步{
SharedReferences prefs=等待SharedReferences.getInstance();
email=prefs.getString(“userEmail”);
password=prefs.getString(“userPassword”);
int clubid=prefs.getInt(“clubid”);
印刷品(clubid);
设置状态(){
userid=prefs.getInt(“userid”);
});
布尔a=假;
for(玩家中的var项目){
如果(项==null){
a=真;
}
}
如果(a==true){
弗拉特