【问题标题】:How i can add a saved items to favorite section in Flutter?如何将保存的项目添加到 Flutter 中的收藏夹部分?
【发布时间】:2021-11-18 14:04:36
【问题描述】:

我目前正在学习颤振和飞镖。我搜索了但没找到。

我想在列表中的名字旁边放一个收藏按钮 和 当点击它时,我只想让它对另一页上的收藏夹进行排序。

这是我的代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  AnaEkran createState() => AnaEkran();
}


class AnaEkran extends State<HomeScreen> {
  static List<String> mainDataList = [
    "Apple",
    "Apricot",
    "Banana",
    "Blackberry",
    "Coconut",
    "Date",
    "Fig",
    "Gooseberry",
    "Grapes",
    "Lemon",
    "Litchi",
    "Mango",
    "Orange",
    "Papaya",
    "Peach",
    "Pineapple",
    "Pomegranate",
    "Starfruit"
  ];
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
          appBar: AppBar(
            title: Text('NickName Generator'),
            backgroundColor: Colors.deepPurple,
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.article_rounded)),
                Tab(icon: Icon(Icons.favorite)),
              ],
            ),
          ),
          body: ListView.builder(
            itemCount: mainDataList.length,
            itemBuilder: (context, index) {
           return Card (
             child: Padding(
             padding: const EdgeInsets.all(20.0),
                child: Text(mainDataList[index],style: TextStyle(fontSize: 19.0),),

             ),

        );
       },
      ),
    ),
    );
  }
}

这就是它的外观。相同的列表出现在第二页,但我只想将最喜欢的词添加到那里。

first screen

second screen

【问题讨论】:

    标签: java android flutter dart mobile


    【解决方案1】:

    我将尝试解释每个必需的步骤,请耐心等待。

    首先,您必须创建一个新列表,这将是最喜欢的字符串列表

      List<String> mainDataList = [
        "Apple",
        "Apricot",
        "Banana",
        "Blackberry",
        "Coconut",
        "Date",
        "Fig",
        "Gooseberry",
        "Grapes",
        "Lemon",
        "Litchi",
        "Mango",
        "Orange",
        "Papaya",
        "Peach",
        "Pineapple",
        "Pomegranate",
        "Starfruit"
      ];
    
      List<String> favoriteDataList = [];
    

    现在,作为 Scaffold 的主体,您必须添加一个 TabBarView 小部件,其中包含一个小部件列表。此列表中的小部件数量必须与您在 TabBar 中添加的选项卡数量相匹配,因为每当您点击其中的一个选项卡时,它都会移动到与索引匹配的 TabBarView 小部件。

    因此,您的 Scaffold 的主体应该如下所示:

    TabBarView(
          children: [
            ListView.builder(
              itemCount: mainDataList.length,
              itemBuilder: (context, index) {
                return Card(
                  child: Row(
                    children: [
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.all(20.0),
                          child: Text(
                            mainDataList[index],
                            style: const TextStyle(fontSize: 19.0),
                          ),
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          setState(() {
                            favoriteDataList.add(mainDataList[index]);
                          });
                        },
                        style: ButtonStyle(
                          backgroundColor: MaterialStateProperty.all<Color>(
                            Colors.deepPurple,
                          ),
                        ),
                        child: const Icon(
                          Icons.favorite,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
            favoriteDataList.isEmpty
                ? const Center(
                    child: Text(
                      'There are no favorites yet!',
                      style: TextStyle(color: Colors.black),
                    ),
                  )
                : ListView.builder(
                    itemCount: favoriteDataList.length,
                    itemBuilder: (context, index) {
                      return Card(
                        child: Row(
                          children: [
                            Expanded(
                              child: Padding(
                                padding: const EdgeInsets.all(20.0),
                                child: Text(
                                  favoriteDataList[index],
                                  style: const TextStyle(fontSize: 19.0),
                                ),
                              ),
                            ),
                            ElevatedButton(
                              onPressed: () {
                                setState(() {
                                  favoriteDataList
                                      .remove(favoriteDataList[index]);
                                });
                              },
                              style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all<Color>(
                                  Colors.deepPurple,
                                ),
                              ),
                              child: const Icon(
                                Icons.remove,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
          ],
        ),
    

    当然,那里有很多代码,我将把它分成几部分以便更好地解释它。 如您所见,首先我们在 TabBarView 的子项中有两个小部件,第一个是您拥有的那个,存在一些差异,因为我添加了一个 Row 并在其中添加了一个 ElevatedButton,它将处理将所需元素添加到收藏列表:

    ElevatedButton(
        onPressed: () {
            setState(() {
            favoriteDataList.add(mainDataList[index]);
            });
        },
        style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all<Color>(
            Colors.deepPurple,
            ),
        ),
        child: const Icon(
            Icons.favorite,
            color: Colors.white,
        ),
    ),
    

    所以,这个按钮的重要部分是onPressed方法,既然你已经构建了一个StatefulWidget,我们可以知道状态已经改变,使用setState方法,它接收一个函数。你为什么需要这个?因为,你需要一种方式来说明状态已经改变的 UI,所以它必须重建。 例如,在 StatelessWidget 中,您没有 setState 方法,因此如果不使用某些特定的 Widget 或某些特定的状态管理解决方案(如 BLoC),您将无法更新 UI。 现在,当用户按下这个收藏按钮时,我们将利用我们刚刚按下的元素的索引,将 mainDataList 中的选定项目添加到收藏夹数据列表中。而且我之前提到过,由于状态改变了,UI会重建,所以当你点击最喜欢的Tab时,你会看到被选中的项目已经被添加了。

    第二个标签视图中的 ElevatedButton,有一些小的区别

    ElevatedButton(
        onPressed: () {
        setState(() {
            favoriteDataList
                .remove(favoriteDataList[index]);
        });
        },
        style: ButtonStyle(
        backgroundColor:
            MaterialStateProperty.all<Color>(
            Colors.deepPurple,
        ),
        ),
        child: const Icon(
        Icons.remove,
        color: Colors.white,
        ),
    ),
    

    除了不同的Icon,我们不想添加元素,而是想要移除它们,所以每当我们按下按钮时,位于同一索引中的项目将从喜爱数据列表中移除。

    如果 favoriteDataList 不是,我还使用三元运算符来显示一个小部件:

    favoriteDataList.isEmpty
        ? const Center(
            child: Text(
                'There are no favorites yet!',
                style: TextStyle(color: Colors.black),
            ),
            )
        : ListView.builder(
    

    如果为空,我们显示 Center... 如果不是,则 ListView...

    这几乎就是全部了,当然,此代码还有一些改进,例如,如果您在第一个选项卡中多次点击同一项目,它将多次添加到收藏列表中。但我认为该示例有效,您将能够使用它并修复它!

    抱歉,帖子太长了,希望对你有帮助!

    【讨论】:

    • 首先非常感谢您。你解释得很好。我希望我会像你一样。我是新来的颤振。我注意到的一件事是,当我单击收藏按钮两次时,它会将单词添加到列表中两次。
    • for(int i=0;i
    • 我将此块添加到收藏列表中,但它不起作用:d
    • 不客气!别担心我没那么好,你要坚持练习!是的,这是我在答案末尾提到的问题之一,您只需要找到一种方法来检查该项目是否已经在列表中,然后再添加它。您使用的 for 循环存在一些问题:1)您在两种情况下都添加了项目 2)您正在迭代 favouriteDataList,并且如果该项目不在您尝试添加的 mainDataList 中它,这是没有意义的,因为收藏列表中的每个项目都将在主列表中
    • 我认为您可以使用两个 for 循环来实现您想要的,一个用于迭代 mainDataList 并在其中一个,另一个迭代 favouriteDataList 并检查您要添加的项目是否已存在于 favoriteDataList .这是检查列表中是否存在项目的另一种简单方法: if (!favoriteDataList.contains(mainDataList[index])) { favoriteDataList.add(mainDataList[index]);在这里,我只是检查要添加到列表中的项目是否已经存在,因此如果不存在,请将其添加到列表中。无论如何,继续尝试使用 for 循环!
    猜你喜欢
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多