【问题标题】:Make favorite function button on flutter app在 Flutter 应用上制作收藏功能按钮
【发布时间】:2020-04-23 02:38:39
【问题描述】:

我是 Flutter 初学者。我正在尝试制作 News Feeder 应用程序。 我想在我的应用程序的每个列表上收藏功能按钮。 但我不知道怎么做。 我试图在每个列表上显示最喜欢的图标。但它不起作用。 我想选择喜欢的按钮相乘。

你能帮忙吗?

这里是代码。

此代码用于将新闻标题和缩略图显示为列表。 我想把最喜欢的图标和工作“主动和非主动功能”。 newslist_screen.dart

import 'package:flutter/material.dart';

import 'package:technewsfeeder/webview_screen.dart';
import 'package:technewsfeeder/fetch_newsdata.dart';

class NewsListScreen extends StatefulWidget {
  // "static const" is always as this value.
  static const String id = 'newslist_screen';

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

class _NewsListScreenState extends State<NewsListScreen> {

  Future<List<NewsDataList>> _savedList;

  // Animation controller init method
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Tech News App'),
        ),
      body: FutureBuilder(
          future: fetchNewsData(),
          builder: (context, snapshot) {
            return snapshot.data != null
                ? listViewWidget(snapshot.data)
                : Center(child: CircularProgressIndicator());
          }),
      );
  }

  Widget listViewWidget(List<NewsDataList> article) {
    return Container(
      child: ListView.builder(
          itemCount: 20,
          padding: const EdgeInsets.all(2.0),
          itemBuilder: (context, position) {
            return Card(
              child: ListTile(
                title: Text(
                  '${article[position].title}',
                  style: TextStyle(
                      fontSize: 18.0,
                      color: Colors.black,
                      fontWeight: FontWeight.bold),
                ),
                leading: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: SizedBox(
                    child: article[position].urlToImage == null
                        ? Image(
                      image: AssetImage(''),
                    )
                        : Image.network('${article[position].urlToImage}'),
                    height: 100.0,
                    width: 100.0,
                  ),
                ),

                  // *******
                  // I would like to put Favorite function here.
                  // *****

                onTap: () {
                  print(article[position].url);
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => WebViewScreen(url: article[position].url)),
                  );
                },
              ),
            );
          }),
    );
  }

  }

}

这是从 URL 中获取 Json 数据。

import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

class NewsDataList {

  final String title;
  final String url;
  final String urlToImage;

  NewsDataList({this.title, this.url, this.urlToImage});

  factory NewsDataList.fromJson(Map<String, dynamic> json) {
    return NewsDataList(
      title: json['title'] as String,
      url: json['url'] as String,
      urlToImage: json['urlToImage'] as String,
    );
  }
}


Future<List<NewsDataList>> fetchNewsData() async {

  List<NewsDataList> list;
  String url = "http://newsapi.org/v2/top-headlines?country=jp&category=technology&apiKey=f289d460a5f94d4087d54cd187becceb";
  var res = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});

  print(res.body);

  if(res.statusCode == 200){
    var data = json.decode(res.body);
    var rest = data["articles"] as List;
    print(rest);
    list = rest.map<NewsDataList>((json) => NewsDataList.fromJson(json)).toList();
    return list;
  } else {
    throw Exception('Failed to load album');
  }
}

V/r,

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    以下是设置收藏按钮的方法。 从列表 tile 构造函数中,我们可以使用尾随小部件来设置收藏按钮 常量

    ListTile(
    
        {Key key,
        Widget leading,
        Widget title,
        Widget subtitle,
        Widget trailing,
        bool isThreeLine: false,
        bool dense,
        EdgeInsetsGeometry contentPadding,
        bool enabled: true,
        GestureTapCallback onTap,
        GestureLongPressCallback onLongPress,
        bool selected: false}
    
    ) 
    

    首先设置您的列表磁贴

    ListTile(
                    leading: FlutterLogo(),
                    title: Text("article Title here"),
                    trailing: IconButton(
                        icon: Icon(
                          Icons.favorite,
                         color: _selectedIndex != null && _selectedIndex == position
                                ? Colors.redAccent
                            : Colors.grey,
                        ),
                        onPressed: (){
                       _onSelected(position);})
    

    那么如何在点击时更改图标颜色

    int _selectedIndex;
         _onSelected(int index) {
            //https://inducesmile.com/google-flutter/how-to-change-the-background-color-of-selected-listview-in-flutter/
            setState(() {
              _selectedIndex = index;
            });
          }
    

    【讨论】:

    • 感谢您的回复!我试过了 :) 但我想点击 IconButton 并设置多个状态。
    • 根据我的回答,您根据列表中的索引一一设置“最喜欢”文章的状态。您说的不止一个是什么意思?
    • 当用户将文章设置为收藏时,您必须保留/保存数据,然后在加载列表时,您可以检查用户是否已保存文章并更改图标颜色
    猜你喜欢
    • 2023-01-22
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多