如何在Flutter中将列表恢复到开头?

huangapple go评论66阅读模式
英文:

How to revert the list to the beginning on Flutter?

问题

尝试使用按钮来排序整数值列表,当升序排列时,它可以工作,但再次按下“Sort Value”按钮返回原始状态时无法工作,卡住了。

初始结果

按下“Sort Value”按钮后的结果

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class Product {
  final String name;
  final String category;
  final int value;

  Product({
    required this.name,
    required this.category,
    required this.value,
  });
}

List<Product> productlist = [
  Product(name: 'Sandwich', category: 'Food', value: 2),
  Product(name: 'Fish', category: 'Food', value: 1),
  Product(name: 'Vegetable', category: 'Food', value: 9),
  Product(name: 'Meat', category: 'Food', value: 13),
  Product(name: 'Book', category: 'Item', value: 4),
  Product(name: 'Hammer', category: 'Item', value: 6),
  Product(name: 'Pen', category: 'Item', value: 5),
  Product(name: 'Car', category: 'Vehicle', value: 8),
  Product(name: 'Bike', category: 'Vehicle', value: 14),
  Product(name: 'Motor', category: 'Vehicle', value: 0),
  Product(name: 'Boat', category: 'Vehicle', value: 25),
];

class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final List<String> categories = ['Food', 'Item', 'Vehicle'];
  List<String> selectedCategories = [];
  bool isActive = true;

  @override
  Widget build(BuildContext context) {
    final filterProducts = productlist.where((product) {
      return selectedCategories.isEmpty ||
          selectedCategories.contains(product.category);
    }).toList();
    return Scaffold(
        appBar: AppBar(
          title: const Text("Filter Sorting"),
          centerTitle: true,
        ),
        body: Column(
          children: [
            Container(
                padding: const EdgeInsets.all(8),
                margin: const EdgeInsets.all(8),
                child: Row(
                  children: [
                    Expanded(
                        flex: 3,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: categories
                              .map((category) => FilterChip(
                                  selected:
                                      selectedCategories.contains(category),
                                  label: Text(category),
                                  onSelected: (selected) {
                                    setState(() {
                                      if (selected) {
                                        selectedCategories.add(category);
                                      } else {
                                        selectedCategories.remove(category);
                                      }
                                    });
                                  }))
                              .toList(),
                        )),
                    Expanded(
                      flex: 1,
                      child: ElevatedButton(
                          onPressed: () {
                            setState(() {
                              if (isActive) {
                                productlist
                                    .sort((b, a) => b.value.compareTo(a.value));
                              } else {
                                productlist.sort((a, b) =>
                                    a.value.compareTo(b.value));
                              }
                              isActive = !isActive;
                            });
                          },
                          child: const Text('Sort Value, \nLow to High',
                              style: TextStyle(fontSize: 10))),
                    ),
                  ],
                )),
            Expanded(
                child: ListView.builder(
                    itemCount: filterProducts.length,
                    itemBuilder: ((context, index) {
                      final product = filterProducts[index];
                      return Card(
                          elevation: 8,
                          margin: const EdgeInsets.all(8),
                          child: Container(
                            decoration: BoxDecoration(color: Colors.blue),
                            child: ListTile(
                                contentPadding: const EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 10),
                                title: Text(
                                  product.name,
                                  style: const TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ),
                                subtitle: Text(
                                  '${product.value}',
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                  ),
                                )),
                          ));
                    })))
          ],
        ));
  }
}

我需要按升序排列顺序,然后还原整个列表,然后重复此操作。

英文:

Trying to use Button to sort the int value list, it works when ascending the order, but it doesn't work when going back to the original state by pressing the Sort Value button once more, stuck.

Initial Outcome

Outcome after Sort Value button pressed

import &#39;package:flutter/material.dart&#39;;
void main() {
runApp(MaterialApp(home: MyApp()));
}
class Product {
final String name;
final String category;
final int value;
Product({
required this.name,
required this.category,
required this.value,
});
}
List&lt;Product&gt; productlist = [
Product(name: &#39;Sandwich&#39;, category: &#39;Food&#39;, value: 2),
Product(name: &#39;Fish&#39;, category: &#39;Food&#39;, value: 1),
Product(name: &#39;Vegetable&#39;, category: &#39;Food&#39;, value: 9),
Product(name: &#39;Meat&#39;, category: &#39;Food&#39;, value: 13),
Product(name: &#39;Book&#39;, category: &#39;Item&#39;, value: 4),
Product(name: &#39;Hammer&#39;, category: &#39;Item&#39;, value: 6),
Product(name: &#39;Pen&#39;, category: &#39;Item&#39;, value: 5),
Product(name: &#39;Car&#39;, category: &#39;Vehicle&#39;, value: 8),
Product(name: &#39;Bike&#39;, category: &#39;Vehicle&#39;, value: 14),
Product(name: &#39;Motor&#39;, category: &#39;Vehicle&#39;, value: 0),
Product(name: &#39;Boat&#39;, category: &#39;Vehicle&#39;, value: 25),
];
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
State&lt;MyApp&gt; createState() =&gt; _MyAppState();
}
class _MyAppState extends State&lt;MyApp&gt; {
final List&lt;String&gt; categories = [&#39;Food&#39;, &#39;Item&#39;, &#39;Vehicle&#39;];
List&lt;String&gt; selectedCategories = [];
bool isActive = true;
@override
Widget build(BuildContext context) {
final filterProducts = productlist.where((product) {
return selectedCategories.isEmpty ||
selectedCategories.contains(product.category);
}).toList();
return Scaffold(
appBar: AppBar(
title: const Text(&quot;Fitler Sorting&quot;),
centerTitle: true,
),
body: Column(
children: [
Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
flex: 3,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: categories
.map((category) =&gt; FilterChip(
selected:
selectedCategories.contains(category),
label: Text(category),
onSelected: (selected) {
setState(() {
if (selected) {
selectedCategories.add(category);
} else {
selectedCategories.remove(category);
}
});
}))
.toList(),
)),
Expanded(
flex: 1,
child: ElevatedButton(
/** */
onPressed: () {
setState(() {
if (isActive) {
productlist
.sort((b, a) =&gt; b.value.compareTo(a.value));
} else {
productlist.toList();
}
});
},
child: const Text(&#39;Sort Value, \nLow to High&#39;,
style: TextStyle(fontSize: 10))),
),
],
)),
Expanded(
child: ListView.builder(
itemCount: filterProducts.length,
itemBuilder: ((context, index) {
final product = filterProducts[index];
return Card(
elevation: 8,
margin: const EdgeInsets.all(8),
child: Container(
decoration: BoxDecoration(color: Colors.blue),
child: ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
title: Text(
product.name,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
subtitle: Text(
&#39;${product.value}&#39;,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
)),
));
})))
],
));
}
}

I need to arrange the order ascendingly, then revert the whole list, rinse and repeat.

答案1

得分: 1

在列表首次创建或修改时,保存另一个变量的副本,例如

originalList = productlist.toList();

这样你的程序就变成了:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class Product {
  final String name;
  final String category;
  final int value;

  Product({
    required this.name,
    required this.category,
    required this.value,
  });
}

List<Product> productlist = [
  Product(name: 'Sandwich', category: 'Food', value: 2),
  Product(name: 'Fish', category: 'Food', value: 1),
  Product(name: 'Vegetable', category: 'Food', value: 9),
  Product(name: 'Meat', category: 'Food', value: 13),
  Product(name: 'Book', category: 'Item', value: 4),
  Product(name: 'Hammer', category: 'Item', value: 6),
  Product(name: 'Pen', category: 'Item', value: 5),
  Product(name: 'Car', category: 'Vehicle', value: 8),
  Product(name: 'Bike', category: 'Vehicle', value: 14),
  Product(name: 'Motor', category: 'Vehicle', value: 0),
  Product(name: 'Boat', category: 'Vehicle', value: 25),
];

class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final List<String> categories = ['Food', 'Item', 'Vehicle'];
  List<String> selectedCategories = [];
  final originalList = productlist.toList();
  bool isActive = true;

  @override
  Widget build(BuildContext context) {
    final filterProducts = productlist.where((product) {
      return selectedCategories.isEmpty ||
          selectedCategories.contains(product.category);
    }).toList();
    return Scaffold(
        appBar: AppBar(
          title: const Text("Fitler Sorting"),
          centerTitle: true,
        ),
        body: Column(
          children: [
            Container(
                padding: const EdgeInsets.all(8),
                margin: const EdgeInsets.all(8),
                child: Row(
                  children: [
                    Expanded(
                        flex: 3,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: categories
                              .map((category) => FilterChip(
                                  selected: selectedCategories.contains(category),
                                  label: Text(category),
                                  onSelected: (selected) {
                                    setState(() {
                                      if (selected) {
                                        selectedCategories.add(category);
                                      } else {
                                        selectedCategories.remove(category);
                                      }
                                    });
                                  }))
                              .toList(),
                        )),
                    Expanded(
                      flex: 1,
                      child: ElevatedButton(
                        onPressed: () {
                          setState(() {
                            if (isActive) {
                              productlist.sort((b, a) =>
                                  b.value.compareTo(a.value));
                            } else {
                              productlist = originalList.toList();
                            }
                            isActive = !isActive;
                          });
                        },
                        child: const Text('Sort Value, \nLow to High',
                            style: TextStyle(fontSize: 10)),
                      ),
                    ),
                  ],
                )),
            Expanded(
                child: ListView.builder(
                    itemCount: filterProducts.length,
                    itemBuilder: ((context, index) {
                      final product = filterProducts[index];
                      return Card(
                          elevation: 8,
                          margin: const EdgeInsets.all(8),
                          child: Container(
                            decoration: BoxDecoration(color: Colors.blue),
                            child: ListTile(
                                contentPadding: const EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 10),
                                title: Text(
                                  product.name,
                                  style: const TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ),
                                subtitle: Text(
                                  '${product.value}',
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                  ),
                                )),
                          ));
                    })))
          ],
        ));
  }
}
英文:

When the list is first created or modified save a copy of it in another variable, like for example

originalList = productlist.toList();

so your program becomes

import &#39;package:flutter/material.dart&#39;;
void main() {
runApp(MaterialApp(home: MyApp()));
}
class Product {
final String name;
final String category;
final int value;
Product({
required this.name,
required this.category,
required this.value,
});
}
List&lt;Product&gt; productlist = [
Product(name: &#39;Sandwich&#39;, category: &#39;Food&#39;, value: 2),
Product(name: &#39;Fish&#39;, category: &#39;Food&#39;, value: 1),
Product(name: &#39;Vegetable&#39;, category: &#39;Food&#39;, value: 9),
Product(name: &#39;Meat&#39;, category: &#39;Food&#39;, value: 13),
Product(name: &#39;Book&#39;, category: &#39;Item&#39;, value: 4),
Product(name: &#39;Hammer&#39;, category: &#39;Item&#39;, value: 6),
Product(name: &#39;Pen&#39;, category: &#39;Item&#39;, value: 5),
Product(name: &#39;Car&#39;, category: &#39;Vehicle&#39;, value: 8),
Product(name: &#39;Bike&#39;, category: &#39;Vehicle&#39;, value: 14),
Product(name: &#39;Motor&#39;, category: &#39;Vehicle&#39;, value: 0),
Product(name: &#39;Boat&#39;, category: &#39;Vehicle&#39;, value: 25),
];
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
State&lt;MyApp&gt; createState() =&gt; _MyAppState();
}
class _MyAppState extends State&lt;MyApp&gt; {
final List&lt;String&gt; categories = [&#39;Food&#39;, &#39;Item&#39;, &#39;Vehicle&#39;];
List&lt;String&gt; selectedCategories = [];
final originalList = productlist.toList();
bool isActive = true;
@override
Widget build(BuildContext context) {
final filterProducts = productlist.where((product) {
return selectedCategories.isEmpty ||
selectedCategories.contains(product.category);
}).toList();
return Scaffold(
appBar: AppBar(
title: const Text(&quot;Fitler Sorting&quot;),
centerTitle: true,
),
body: Column(
children: [
Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
flex: 3,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: categories
.map((category) =&gt; FilterChip(
selected:
selectedCategories.contains(category),
label: Text(category),
onSelected: (selected) {
setState(() {
if (selected) {
selectedCategories.add(category);
} else {
selectedCategories.remove(category);
}
});
}))
.toList(),
)),
Expanded(
flex: 1,
child: ElevatedButton(
/** */
onPressed: () {
setState(() {
if (isActive) {
productlist
.sort((b, a) =&gt; b.value.compareTo(a.value));
} else {
productlist = originalList.toList();
}
isActive = !isActive;
});
},
child: const Text(&#39;Sort Value, \nLow to High&#39;,
style: TextStyle(fontSize: 10))),
),
],
)),
Expanded(
child: ListView.builder(
itemCount: filterProducts.length,
itemBuilder: ((context, index) {
final product = filterProducts[index];
return Card(
elevation: 8,
margin: const EdgeInsets.all(8),
child: Container(
decoration: BoxDecoration(color: Colors.blue),
child: ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
title: Text(
product.name,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
subtitle: Text(
&#39;${product.value}&#39;,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
)),
));
})))
],
));
}
}
</details>

huangapple
  • 本文由 发表于 2023年6月8日 19:24:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定