Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/196.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
Firebase 颤振对两个列表而不是一个列表进行排序_Firebase_Flutter_Dart_Google Cloud Firestore - Fatal编程技术网

Firebase 颤振对两个列表而不是一个列表进行排序

Firebase 颤振对两个列表而不是一个列表进行排序,firebase,flutter,dart,google-cloud-firestore,Firebase,Flutter,Dart,Google Cloud Firestore,嗨:)我需要帮助对付弗利特,我对这整件事还不熟悉。 我想对列表allGames进行排序,但它也会自动对列表chartGames进行排序。我怎样才能把这两个根本没有联系的东西分开呢 class _GameHistoryScreenState extends State<GameHistoryScreen> { Future resultsLoaded; Future chartResultsLoaded; List<Game> allGames = [];

嗨:)我需要帮助对付弗利特,我对这整件事还不熟悉。 我想对列表
allGames
进行排序,但它也会自动对列表
chartGames
进行排序。我怎样才能把这两个根本没有联系的东西分开呢

class _GameHistoryScreenState extends State<GameHistoryScreen> {
  Future resultsLoaded;
  Future chartResultsLoaded;

  List<Game> allGames = [];
  List<Game> chartGames = [];

  List<Game> incompleteGamesList = [];

  List<Game> completeGamesList = [];

  String dialog;

  bool loading;

  double averageScore;

  double averagePuttsPerHole;

  double averageDerivationPar;

  final String route = GameHistoryScreen.routeName;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    loading = true;
    resultsLoaded = getUsersGamesSnapshot();
    chartResultsLoaded = getUsersGamesSnapshotChart();
  }

  // Gets all games of the user
  Future getUsersGamesSnapshot() async {
    var data = await Provider.of<GameProvider>(context).games;

    setState(() {
      allGames = data;
      loading = false;
    });
  }

  Future getUsersGamesSnapshotChart() async {
    var chartData = await Provider.of<GameProvider>(context).games;

    setState(() {
      chartGames = chartData;
      loading = false;
    });
  }

  static const menuItems = <String>[
    'Datum',
    'Platzname',
    // 'Score',
  ];
  final List<DropdownMenuItem<String>> dropDownMenuItems = menuItems
      .map(
        (String value) => DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        ),
      )
      .toList();

  String btn1SelectedVal = 'Datum';

  void sortList() {
    switch (btn1SelectedVal) {
      case "Datum":
        {
          allGames.sort(
              (game1, game2) => game2.startTime.compareTo(game1.startTime));
          break;
        }
      case "Platzname":
        {
          allGames
              .sort((game1, game2) => game1.courseId.compareTo(game2.courseId));
          break;
        }
      // case "Score":
      //   {
      //     allGames.sort((game1, game2) => game2.strokes.compareTo(game1.strokes));
      //     break;
      //   }
    }
  }

  //  für jedes Element von Games wird der Konstruktor von ChartData mit dem Index und den Daten
  //  aufgerufen. Dieser wird in einer Liste gespeichert und am Ende zurückgegeben
  List<ChartData> createChartList() {
    List<ChartData> list = [];
    for (int i = 0; i < chartGames.length; i++) {
      list.add(ChartData(i, chartGames[i].endScore.toDouble()));
    }
    return list;
  }

  void getButtonNumbers() {
    int holeCounter = 0;
    for (int i = 0; i < chartGames.length; i++) {
      this.averageScore += chartGames[i].endScore;
      for (int m = chartGames[i].startHoleNumber;
          m <= chartGames[i].endHoleNumber;
          m++) {
        this.averagePuttsPerHole +=
            chartGames[i].strokes.getPuttsByHoleNumber(m);
        holeCounter++;
      }
      // this.averageDerivationPar += blub;
    }
    this.averageScore = this.averageScore / chartGames.length;
    this.averagePuttsPerHole = this.averagePuttsPerHole / holeCounter;
  }

  @override
  Widget build(BuildContext context) {
    sortList();
    return MainScaffold(
      title: "Game History",
      child: Column(
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                OutlinedButton(
                    onPressed: () => {},
                    child: Column(
                      children: [Text("blub"), Icon(Icons.score)],
                    )),
                OutlinedButton(
                    onPressed: () => {},
                    child: Column(
                      children: [Text("blub"), Icon(Icons.sports_golf)],
                    )),
                OutlinedButton(
                    onPressed: () => {},
                    child: Column(
                      children: [Text("blub"), Icon(Icons.departure_board)],
                    )),
              ], //"ØScore"
            ),
          ),
          Container(
              height: 200,
              width: MediaQuery.of(context).size.width,
              child: SfCartesianChart(
                primaryXAxis: CategoryAxis(),
                series: <LineSeries<ChartData, int>>[
                  LineSeries<ChartData, int>(
                      animationDuration: 5000,
                      // Bind data source
                      dataSource: createChartList(),
                      xValueMapper: (ChartData sales, _) => sales.number,
                      yValueMapper: (ChartData sales, _) => sales.data)
                ],
              )),
          ListTile(
            title: const Text('Filtern nach:'),
            trailing: DropdownButton<String>(
              // Must be one of items.value.
              value: btn1SelectedVal,
              onChanged: (String newValue) {
                setState(() {
                  btn1SelectedVal = newValue;
                });
              },
              items: this.dropDownMenuItems,
            ),
          ),
          ...allGames.map<Widget>(
            (game) => Card(
              elevation: 5,
              margin: EdgeInsets.symmetric(
                vertical: 5,
                horizontal: 5,
              ),
              child: ListTile(
                leading: CircleAvatar(
                  radius: 30,
                  child: Padding(
                    padding: EdgeInsets.all(6),
                    child: FittedBox(
                      child: Text('${game.endScore}'),
                    ),
                  ),
                ),
                title: FutureBuilder(
                    future: Provider.of<CoursesProvider>(context)
                        .getCourseById(game.courseId),
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        final course = snapshot.data as Course;
                        return Container(
                          height: 25,
                          width: 100,
                          child: AutoSizeText(
                            course.name,
                            style: Theme.of(context).textTheme.headline6,
                            maxLines: 2,
                            overflowReplacement: AutoSizeText(
                              "Error: Name too long",
                              style: TextStyle(
                                  color: Colors.red,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        );
                      } else {
                        return Text(" ");
                      }
                    }),
                subtitle: Text(
                  DateFormat.yMMMd().format(game.startTime),
                ),
                trailing: Container(
                  width: 105,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      2 > 1
                          ? Icon(
                              CustomIcons.singleplayer.icon,
                              color: Colors.deepOrange,
                            )
                          : Icon(
                              CustomIcons.multiplayer.icon,
                              color: Colors.deepOrange,
                            ),
                      game.completed
                          ? Icon(
                              Icons.check_box,
                              color: Colors.green,
                            )
                          : Icon(
                              Icons.check_box_outline_blank,
                              color: Colors.green,
                            ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            // makes no sense but fixes an issue
            child: SizedBox(
              height: 5,
            ),
          ),
        ],
      ),
    );
  }
}

class ChartData {
  ChartData(this.number, this.data);
  final int number;
  final double data;
}

谢谢你的帮助

当您对
所有游戏
进行排序时,其他列表也会发生变化,原因是您正在共享对
游戏提供商
类中原始列表的引用

您应该创建列表的浅层克隆。您可以这样做:

setState(){
allGames=[…数据];//创建一个新的
});
// ...
设置状态(){
chartGames=[…chartData];//创建一个新的
});

您使用相同的表达式分配两个列表,因此它们实际上是相同的(
等待Provider.of(context.games;
)。您可以在提供者中创建两个单独的列表。或者您可以创建一个getter,直接返回列表的排序/筛选版本。

非常感谢!非常感谢你!这真的解决了它:D
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.0.3, on macOS 11.2.3 20D91 darwin-x64, locale en-DE)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✗] Xcode - develop for iOS and macOS
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS development.
      Download at: https://developer.apple.com/xcode/download/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
        sudo xcodebuild -runFirstLaunch
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] VS Code (version 1.54.3)
[✓] Connected device (2 available)

! Doctor found issues in 1 category.