Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.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,我是Flatter的初学者,我编写了一个从api调用json数据的代码,然后执行了,但执行有点慢,在控制台中我发现了一条错误消息,上面说 E/flutter ( 6908): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: setState() called after dispose(): _PlayersCreationDetailsViewState#559ce(lifecycle state: defun

我是Flatter的初学者,我编写了一个从api调用json数据的代码,然后执行了,但执行有点慢,在控制台中我发现了一条错误消息,上面说

E/flutter ( 6908): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: setState() called after dispose(): _PlayersCreationDetailsViewState#559ce(lifecycle state: defunct, not mounted)
E/flutter ( 6908): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 6908): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 6908): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 6908): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1208:9)
E/flutter ( 6908): #1      State.setState (package:flutter/src/widgets/framework.dart:1243:6)
E/flutter ( 6908): #2      _PlayersCreationDetailsViewState.getPlayer (package:footyappp/Fantazyy/players_creation_details_view.dart:101:5)
E/flutter ( 6908): <asynchronous suspension>
E/flutter ( 6908): #3      _PlayersCreationDetailsViewState.getClubIds.<anonymous closure> (package:footyappp/Fantazyy/players_creation_details_view.dart:84:14)
E/flutter ( 6908): #4      State.setState (package:flutter/src/widgets/framework.dart:1244:30)
E/flutter ( 6908): #5      _PlayersCreationDetailsViewState.getClubIds (package:footyappp/Fantazyy/players_creation_details_view.dart:73:5)
E/flutter ( 6908): #6      _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 6908): #7      _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 6908): #8      _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flatter(6908):[ERROR:flatter/lib/ui/ui\u dart\u state.cc(177)]未处理的异常:在dispose()之后调用setState():_PlayersCreationDetailsViewState 359ce(生命周期状态:失效,未安装)
E/flatter(6908):如果对不再出现在小部件树中的小部件(例如,其父小部件不再包含其构建中的小部件)的状态对象调用setState(),则会发生此错误。当代码从计时器或动画回调调用setState()时,可能会发生此错误。
E/flatter(6908):首选解决方案是取消计时器或停止在dispose()回调中侦听动画。另一种解决方案是在调用setState()之前检查该对象的“mounted”属性,以确保该对象仍在树中。
E/flatter(6908):如果调用setState(),则此错误可能表示内存泄漏,因为从树中删除该状态对象后,另一个对象仍保留对此状态对象的引用。为了避免内存泄漏,请考虑在Debug()中中断对该对象的引用。
E/颤振(6908):#0状态。设置状态。(包:flatter/src/widgets/framework.dart:1208:9)
E/flatter(6908):#1 State.setState(包:flatter/src/widgets/framework.dart:1243:6)
E/flatter(6908):#2名玩家创建tailsviewstate.getPlayer(包:footyappp/fantazy/players\u创建\u详细信息\u视图。dart:101:5)
E/颤振(6908):
E/颤振(6908):#3名玩家创建了tailsviewstate.getClubIds。(套餐:footyappp/fantazy/players\u creation\u details\u view.省道:84:14)
E/flatter(6908):#4 State.setState(包:flatter/src/widgets/framework.dart:1244:30)
E/Flatter(6908):#5#玩家创建tailsviewstate.getClubIds(包:footyappp/fantazy/players#创建(细节)视图。dart:73:5)
E/颤振(6908):#6#根运行单位(dart:async/zone.dart:1198:47)
E/flatter(6908):#7_CustomZone.runUnary(dart:async/zone.dart:1100:19)
E/flatter(6908):#8 FutureListener.handleValue(dart:async/future_impl.dart:143:18)
下面是我尝试过的代码:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:footyappp/Fantazyy/Playerrs.dart';
import 'package:footyappp/Fantazyy/club_api.dart';
import 'package:footyappp/Fantazyy/create_team_view.dart';
import 'package:footyappp/Fantazyy/player%20copy.dart';
import 'package:footyappp/Fantazyy/player_lab.dart';
import 'package:footyappp/Key/Key.dart';
import 'package:http/http.dart' as http;

class PlayersCreationDetailsView extends StatefulWidget {

  final List<Playerr> selectedPlayers;
  final int playerIndex;

  const PlayersCreationDetailsView ({
    Key key,
    @required this.selectedPlayers,
    @required this.playerIndex
  })  : super(key: key);

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


class _PlayersCreationDetailsViewState extends State<PlayersCreationDetailsView> {
  bool _sortAsc = false;
  int _sortColumnIndex = 0;
  double _columnWidth  = 40.0;
  double _columnNameWidth  = 60.0;
  double _columnPosWidth  = 80.0;
  PlayersDataSource _playersDataSource;
  List<Playerr> _players = [];
  List<ClubApi> selectedClubs = [];
  List<int> clubIdentifiers = [];
  List<Playerrs> playersjson = [];
  List<Playerr> playersApi = [];
    List<dynamic> playerList ;
   List _table;


  int _rowsPerPage = 20;
   final String apiUrl =
      "https://v3.football.api-sports.io/players?season=2020&league=39";
  
  static const headers = {
    'x-rapidapi-host': "v3.football.api-sports.io",
    //Always make sure to check the api key and the limit of a request in a free api
    'x-rapidapi-key': ApiKey.key
  };

  void _sort<T>(Comparable<T> getField(Playerr p), int columnIndex, bool ascending) {
    _playersDataSource._sort<T>(getField, ascending);
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAsc = ascending ;
    });
  }


  Future<void> getClubIds() async {
    http.Response response = await http.get(
        "https://v3.football.api-sports.io/teams?season=2020&league=39",
        headers: {'x-rapidapi-host': "v3.football.api-sports.io",
          'x-rapidapi-key': ApiKey.key});
    String body = response.body;
    var data = jsonDecode(body);
    List<dynamic> table = data['response'];

    setState(() {
      selectedClubs = table
          .map((dynamic item) => ClubApi.fromJson(item))
          .toList();

      for(var item in selectedClubs){
         clubIdentifiers.add(item.team.id);
      }

      for(var item in clubIdentifiers){
        print("club id"+item.toString());
        this.getPlayer(item);
      }

    });

  }


  Future<void> getPlayer(int id) async {
    http.Response response = await http.get(
      "https://v3.football.api-sports.io/players?season=2020&league=39&team=$id",
        headers: {'x-rapidapi-host': "v3.football.api-sports.io",
    'x-rapidapi-key': ApiKey.key});
    String body = response.body;
    var data = jsonDecode(body);
    List<dynamic> table = data['response'];

    setState(() {
      playersjson = table
          .map((dynamic item) => Playerrs.fromJson(item))
          .toList();

      for(var item in playersjson){
        String pos = item.statistics[0].games.position.toString().substring(9);
        playersApi.add(Playerr(item.player.id,item.player.firstname, item.player.lastname, pos,
            item.statistics[0].team.name,item.statistics[0].games.rating, item.statistics[0].games.appearences,item.statistics[0].goals.total,
            item.statistics[0].goals.assists,item.statistics[0].goals.conceded,
            item.statistics[0].cards.red, item.statistics[0].cards.yellow));
      }
      print(playersApi.length);
      // for(var item in playersApi){
      //   print("position"+item.position.toString());
      // print(item.position.contains("DEFENDER"));
      // }
      for(var item in playersApi){
        print("position"+item.position.toString());

      }
      if (widget.playerIndex < 2) {
        _players = playersApi.where((player) => player

            .position.contains("GOALKEEPER")).toList();
      } else if (widget.playerIndex < 7) {
        _players = playersApi.where((player) => player.position.contains("DEFENDER")).toList();
      } else if (widget.playerIndex < 12) {
        _players = playersApi.where((player) => player.position.contains("MIDFIELDER")).toList();
      } else {
        _players = playersApi.where((player) => player.position.contains("ATTACKER")).toList();
      }

      print("length of selected"+widget.selectedPlayers.length.toString());
     for(var item in widget.selectedPlayers){
       print("selected"+item.toString());
       if(item == null){
         print("hello");
       }else if(item !=null){
         print(item.playerID.toString());
         _players.removeWhere((player) => player.playerID == item.playerID);
       }
     }
      //  widget.selectedPlayers.forEach((selectedPlayer) =>
      //     _players.removeWhere((player) => (player.playerID == selectedPlayer.playerID) && (selectedPlayer.playerID != null)));
      //  print("length of selected"+widget.selectedPlayers.length.toString());
      //filter out players who are already selected

        // for (Playerr player in widget.selectedPlayers) {
        //   _players.remove(player);
        // }
        _playersDataSource = PlayersDataSource(widget.playerIndex, widget.selectedPlayers, _players, context);

    });

  }

@override
  void initState() {
  super.initState();
  this.getClubIds();
    //filter out players by position

  }

  @override
  Widget build(BuildContext context) {
    print(playersApi.length);

    return  playersApi.length == 0
        ? Container(
      color: Colors.white,
      child: Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(
            Color(0xFFe70066),
          ),
        ),
      ),
    )
        : WillPopScope(
      onWillPop: () async => false,
      child: Scaffold(
        body: ListView(
          children: <Widget>[
            PaginatedDataTable(
              columnSpacing: 1.0,
              horizontalMargin: 1.0,
              availableRowsPerPage: [10,20,50],
              rowsPerPage: _rowsPerPage,
              onRowsPerPageChanged: (int value) { setState(() { _rowsPerPage = value; }); },
              sortColumnIndex: _sortColumnIndex,
              sortAscending: _sortAsc,
              header: Text("Players"),
              columns: <DataColumn>[
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: Text("First Name", softWrap: true,)),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<String>((Playerr p) => p.firstName, columnIndex, ascending)
                ),
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: Text("Last Name", softWrap: true,)),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<String>((Playerr p) => p.lastName, columnIndex, ascending)
                ),
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: Text("Position", softWrap: true,)),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<String>((Playerr p) => p.position, columnIndex, ascending)
                ),
                  new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Price")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Playerr p) => p.price, columnIndex, ascending)
                ),
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: Text("Rating", softWrap: true,)),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<String>((Playerr p) => p.rating, columnIndex, ascending)
                ),
               /* new DataColumn(
                    label: new Container(width: _columnWidth , child: new Text("Position")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<String>((Playerr p) => p.position, columnIndex, ascending)
                ),*/
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Team")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<String>((Playerr p) => p.team, columnIndex, ascending)
                ),
                
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Apps")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Playerr p) => p.appearances, columnIndex, ascending)
                ),
              
               /* new DataColumn(
                    label: new Container(width: _columnWidth , child: new Text("Points")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.points, columnIndex, ascending)
                ),
                new DataColumn(
                    label: new Container(width: _columnWidth , child: new Text("Week Points")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.pointsWeek, columnIndex, ascending)
                ),*/
               
               /* new DataColumn(
                    label: new Container(width: _columnWidth , child: new Text("Sub Apps")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.subAppearances, columnIndex, ascending)
                ),*/
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Goals")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Playerr p) => p.goals, columnIndex, ascending)
                ),
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Assists")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Playerr p) => p.assists, columnIndex, ascending)
                ),
                
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Clean")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Playerr p) => p.cleanSheets, columnIndex, ascending)
                ),
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Yellows")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Playerr p) => p.yellowCards, columnIndex, ascending)
                ),
                new DataColumn(
                    label: new Container(width: _columnPosWidth , child: new Text("Reds")),
                    numeric: true,
                    onSort: (int columnIndex, bool ascending) => _sort<num>((Playerr p) => p.redCards, columnIndex, ascending)
                ),
               
              ],
              source: _playersDataSource,
            )
          ],
        )
      )
    );
  }
}

class PlayersDataSource extends DataTableSource {

  PlayersDataSource(this._playerIndex, this._selectedPlayers, this._players, this.context);

  int _playerIndex;
  List<Playerr> _players;
  List<Playerr> _selectedPlayers;

  int _selectedCount = 0;
  var context;
  double _columnWidth  = 40.0;
  double _columnNameWidth  = 60.0;
  double _columnPosWidth  = 80.0;

  void _sort<T>(Comparable<T> getField(Playerr p), bool ascending) {
    _players.sort((Playerr a, Playerr b) {
      if (!ascending) {
        final Playerr c = a;
        a = b;
        b = c;
      }
      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    notifyListeners();
  }

  DataCell getCell(String text) {
    return DataCell(Container(width: _columnPosWidth, child: Text(text, overflow: TextOverflow.fade, softWrap: false,)));
  }

  


  @override
  DataRow getRow(int index) {
    assert(index >= 0);
    if (index >= _players.length)
      return null;
    final Playerr player = _players[index];
    return DataRow.byIndex(
      onSelectChanged: (bool) {
        _players.removeAt(index);
        _selectedPlayers[_playerIndex] = player;
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) {return CreateTeamView(players: _players, selectedPlayers: _selectedPlayers,);}));
      },
        index: index,
        cells: <DataCell>[
          getCell(player.firstName),
          getCell(player.lastName),
          getCell(player.position),
         getCell('${player.price}'),
          getCell('${player.rating}'),
         // getCell('${player.isFresher}'),
          getCell('${player.team}'),
          //getCell('${player.points}'),
         // getCell('${player.pointsWeek}'),
          getCell('${player.appearances}'),
         // getCell('${player.subAppearances}'),
          getCell('${player.goals}'),
          getCell('${player.assists}'),
          getCell('${player.cleanSheets}'),
         // getCell('${player.motms}'),
          getCell('${player.yellowCards}'),
          getCell('${player.redCards}'),
        //  getCell('${player.ownGoals}'),
        ]
    );
  }

  @override
  int get rowCount => _players.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => _selectedCount;


}
导入'dart:convert';
进口“包装:颤振/材料.省道”;
导入“包:footyappp/fantazy/players.dart”;
进口“包装:footyappp/Fantazy/club_api.dart”;
导入“包:footyappp/fantazy/create_team_view.dart”;
导入“包:footyappp/fantazy/player%20copy.dart”;
导入“包:footyappp/fantazy/player_lab.dart”;
导入“包:footyappp/Key/Key.dart”;
将“package:http/http.dart”导入为http;
类Players CreationDetailsView扩展StatefulWidget{
最终选定的球员名单;
最终整数playerIndex;
const Players CreationDetailsView({
关键点,
@需要此选项。选择玩家,
@需要此.playerIndex
}):super(key:key);
@凌驾
_PlayerCreationDetailsViewState()=>\u PlayerCreationDetailsViewState();
}
类_PlayersCreationDetailsViewState扩展状态{
bool _sortAsc=false;
int _sortColumnIndex=0;
双柱宽=40.0;
双_columnNameWidth=60.0;
双柱PosWidth=80.0;
PlayerDataSource _PlayerDataSource;
列出_玩家=[];
列出所选俱乐部=[];
列表俱乐部标识符=[];
列表播放器JSON=[];
列表播放器API=[];
列表玩家列表;
列表表;
int_rowsPerPage=20;
最终字符串apirl=
"https://v3.football.api-sports.io/players?season=2020&league=39";
静态常量头={
'x-rapidapi-host':“v3.football.api sports.io”,
//始终确保检查免费api中的api密钥和请求限制
“x-rapidapi-key”:ApiKey.key
};
void\u排序(可比较的getField(Playerr p)、int-columnIndex、bool升序){
_PlayerDataSource.\u排序(getField,升序);
设置状态(){
_sortColumnIndex=列索引;
_sortAsc=上升;
});
}
Future getClubIds()异步{
http.Response-Response=等待http.get(
"https://v3.football.api-sports.io/teams?season=2020&league=39",
标题:{'x-rapidapi-host':“v3.football.api sports.io”,
“x-rapidapi-key”:ApiKey.key});
字符串体=response.body;
var数据=jsonDecode(主体);
列表=数据[‘响应’];
设置状态(){
selectedClubs=表格
.map((动态项)=>ClubApi.fromJson(项))
.toList();
对于(所选俱乐部中的var项目){
添加(item.team.id);
}
for(分类标识符中的var项目){
打印(“俱乐部id”+item.toString());
这个.getPlayer(项目);
}
});
}
未来getPlayer(int-id)异步{
http.Response-Response=等待http.get(
"https://v3.football.api-sports.io/players?season=2020&league=39&team=$id“,
标题:{'x-rapidapi-host':“v3.football.api sports.io”,
“x-rapidapi-key”:ApiKey.key});
字符串体=response.body;
var数据=jsonDecode(主体);
列表=数据[‘响应’];
设置状态(){
playersjson=表格
.map((动态项)=>Playerrs.fromJson(项))
.toList();
for(playersjson中的变量项){
字符串pos=item.statistics[0].games.position.toString().substring(9);
playersApi.add(Playerr(item.player.id、item.player.firstname、item.player.lastname、pos、,
item.statistics[0]。team.name,item.statistics[0]。games.rating,item.statistics[0]。games.Appeares,item.statistics[0]。goals.total,
item.statistics[0]。进球。助攻,item.statistics[0]。进球。失球,
item.statistics[0]。cards.red,item.statistics[0]。cards.yellow));
}
打印(播放器API.长度);
//用于(PlayerAPI中的变量项){
//打印(“position”+item.position.toString());
//打印(项目位置包含(“DEFENDER”);
// }
用于(PlayerAPI中的变量项){
打印(“位置”+item.position.toSt
  if(mounted){
      setState((){})
    }