如何在Flutter VSCODE中将列表重置为原始状态

ttcibm8c  于 2023-04-07  发布在  Flutter
关注(0)|答案(1)|浏览(119)

我一直在摆弄我在网上找到的信息,但还没有能够使我的代码工作,请帮助。
我需要我的列表能够恢复到其原始内容。
以下是我目前为止的代码:

import 'package:flutter/material.dart';

List<String> items = ["CGS 1540", "COP 2512", "COP 2513", "CIS 3213",
"CGS 3303", "CIS 3363", "COP 3515", "CEN 3722", "CGS 3853", "CNT 4104",
"CNT 4403", "COP 4538", "CNT 4603", "CIS 4935", "COP 4703" ];

void main() {

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

   @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: const MyStatefulWidget(),
      ),
    );
  }

}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

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

class _MyStatefulWidgetState extends State<StatefulWidget> {
 List<String>initialData = [];
 
  @override
  void initState() {
    fillInitialData();
    super.initState();
  }

  fillInitialData() {
    initialData.addAll(items);
  }
  

  @override
  Widget build(BuildContext context) {
    const title = 'Course List';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(title),
        ),
      
        body: ListView.builder(
          itemCount: items.length,
          padding: const EdgeInsets.symmetric(vertical:16),
          prototypeItem: ListTile(
            title: Text(items.first),
          ),
          itemBuilder: (context, index) {
            return Dismissible(
              background: Container(
                child: Text('Delete ${items[index]}',
                style: TextStyle(color: Colors.white),
                ),
                color: Colors.red,
              ),
              secondaryBackground:Container(
                child: Text('Archive ${items[index]}',
                style: TextStyle(color: Colors.white),
                ),
                alignment: Alignment.centerRight,
                color: Colors.yellow,
              ),
              key: ValueKey<String>(items[index]),
              onDismissed: (DismissDirection direction){
                if(direction == DismissDirection.startToEnd) {  
                setState(() {
                  String deletedItem = items.removeAt(index);
                  
                   ScaffoldMessenger.of(context)
                   ..removeCurrentSnackBar()
                   ..showSnackBar(
                  
                  SnackBar(
                    duration: const Duration(
                      seconds: 2,
                    ),
                  content: Text('$deletedItem deleted'),
                  action: SnackBarAction(
                  label: 'Undo',
                    onPressed: (){
                      setState(() => items.insert(index, deletedItem));
                    },

                  ),
                  )

            
                   );

              },
            
            );
            } 
            
            else if (direction == DismissDirection.endToStart){
              setState(() {
                  String deletedItem = items.removeAt(index);
                  
                   ScaffoldMessenger.of(context)
                   ..removeCurrentSnackBar()
                   ..showSnackBar(
                  
                  SnackBar(
                    duration: const Duration(
                      seconds: 2,
                    ),
                  content: Text('$deletedItem Archived'),
                  action: SnackBarAction(
                  label: 'Undo',
                    onPressed: (){
                      setState(() => items.insert(index, deletedItem));
                    },

                  ),
                  )
            
                   );

              },
            
            );
            }
          },                  
               child: ListTile(
                title: Text(
                   '${items[index]}',
                )
              )
        );
          },
    ),

      floatingActionButton: FloatingActionButton(
        onPressed: (){
          setState(() {
            initialData.clear();
            fillInitialData();
          });
        },
        tooltip: 'Reset',
        child: const Icon(Icons.autorenew),
      ),

    ),
    );
  }
  

}

我已经看过了我在这里看到的许多帖子,但它们要么是滑块或数字,所以我卡住了,请帮助我弄清楚如何使用操作按钮将列表重置为原始状态,然后再进行任何删除存档。

nxowjjhe

nxowjjhe1#

因此,本质上需要注意的一件事是,items.remove实际上修改了原始列表,这意味着当您从列表items中删除元素时,删除的元素将不再存在。
由于您已经在initialData中复制了这些项,因此对当前代码的一个快速修复方法是清除这些项并将其重新添加到items列表中,因为这是小部件的状态 * 所依赖的 *

floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              items.clear();
              items.addAll(initialData);
              initialData.clear();
              fillInitialData();
            });
          },
          tooltip: 'Reset',
          child: const Icon(Icons.autorenew),
        ),

但这段代码可以更清晰,如果你感兴趣,这里是如何(我会尽我所能解释)

有几件事可以改进:
1.你的状态不应该依赖于一个全局变量,你可以将items列表传递给你的有状态小部件
1.状态对象应该是处理状态的对象,这意味着无论你的
以下是我对您的代码所做的更改,以使其更清晰
首先,我将items列表作为字符串的常量列表,它将被用作 * 单一真实值源 *

const List<String> items = [
  "CGS 1540",
  "COP 2512",
  "COP 2513",
  "CIS 3213",
  "CGS 3303",
  "CIS 3363",
  "COP 3515",
  "CEN 3722",
  "CGS 3853",
  "CNT 4104",
  "CNT 4403",
  "COP 4538",
  "CNT 4603",
  "CIS 4935",
  "COP 4703"
];

其次,我向有状态小部件添加了最后一个list属性,并使state类扩展了State<MyStatefulWidget>,以便我们可以在state对象中使用该属性。

class MyStatefulWidget extends StatefulWidget {
  final List<String> items;
  const MyStatefulWidget({super.key, required this.items});

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

class MyStatefulWidgetState extends State<MyStatefulWidget> {
...
}

现在你对你的状态所做的任何事情都不会影响你原来的小部件,这样你就可以在不同的列表中重用相同的小部件。所以,我在state类中添加了一个字符串属性的List,它将用于状态,所以每当状态需要更新时,那个列表应该被修改
所以像这样的事情现在可以做了

List<String> items = [];

  @override
  void initState() {
    fillInitialData();
    super.initState();
  }

  fillInitialData() {
    items.clear();
    items.addAll(widget.items);
  }

....

 floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              fillInitialData();
            });
          },
          tooltip: 'Reset',
          child: const Icon(Icons.autorenew),
),

最后,这里是修改后的完整代码

完整代码

import 'package:flutter/material.dart';

const List<String> items = [
  "CGS 1540",
  "COP 2512",
  "COP 2513",
  "CIS 3213",
  "CGS 3303",
  "CIS 3363",
  "COP 3515",
  "CEN 3722",
  "CGS 3853",
  "CNT 4104",
  "CNT 4403",
  "COP 4538",
  "CNT 4603",
  "CIS 4935",
  "COP 4703"
];

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: MyStatefulWidget(
          items: items,
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  final List<String> items;
  const MyStatefulWidget({super.key, required this.items});

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

class MyStatefulWidgetState extends State<MyStatefulWidget> {
  List<String> items = [];

  @override
  void initState() {
    fillInitialData();
    super.initState();
  }

  fillInitialData() {
    items.clear();
    items.addAll(widget.items);
  }

  @override
  Widget build(BuildContext context) {
    const title = 'Course List';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(title),
        ),
        body: ListView.builder(
          itemCount: items.length,
          padding: const EdgeInsets.symmetric(vertical: 16),
          prototypeItem: ListTile(
            title: Text(items.first),
          ),
          itemBuilder: (context, index) {
            return Dismissible(
                background: Container(
                  color: Colors.red,
                  child: Text(
                    'Delete ${items[index]}',
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
                secondaryBackground: Container(
                  alignment: Alignment.centerRight,
                  color: Colors.yellow,
                  child: Text(
                    'Archive ${items[index]}',
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
                key: ValueKey<String>(items[index]),
                onDismissed: (DismissDirection direction) {
                  if (direction == DismissDirection.startToEnd) {
                    setState(
                      () {
                        String deletedItem = items.removeAt(index);

                        ScaffoldMessenger.of(context)
                          ..removeCurrentSnackBar()
                          ..showSnackBar(SnackBar(
                            duration: const Duration(
                              seconds: 2,
                            ),
                            content: Text('$deletedItem deleted'),
                            action: SnackBarAction(
                              label: 'Undo',
                              onPressed: () {
                                setState(
                                    () => items.insert(index, deletedItem));
                              },
                            ),
                          ));
                      },
                    );
                  } else if (direction == DismissDirection.endToStart) {
                    setState(
                      () {
                        String deletedItem = items.removeAt(index);

                        ScaffoldMessenger.of(context)
                          ..removeCurrentSnackBar()
                          ..showSnackBar(SnackBar(
                            duration: const Duration(
                              seconds: 2,
                            ),
                            content: Text('$deletedItem Archived'),
                            action: SnackBarAction(
                              label: 'Undo',
                              onPressed: () {
                                setState(
                                    () => items.insert(index, deletedItem));
                              },
                            ),
                          ));
                      },
                    );
                  }
                },
                child: ListTile(
                    title: Text(
                  items[index],
                )));
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              fillInitialData();
            });
          },
          tooltip: 'Reset',
          child: const Icon(Icons.autorenew),
        ),
      ),
    );
  }
}

相关问题