在flutter应用上设置收藏夹功能按钮

问题描述 投票:0回答:1

我是Flutter初学者。我想在我的应用程序中的每个列表上设置收藏夹功能按钮,但我不知道如何使它,我试图在每个列表上显示收藏夹图标,但它不工作,我想选择收藏夹按钮乘。但它不工作,我想选择收藏夹按钮乘。

你能帮帮我吗?

下面是代码。

这段代码是显示新闻标题和缩略图作为列表,我想把最喜欢的Icon和工作 "主动和非主动功能".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');
  }
}

Vr,

flutter dart
1个回答
0
投票

这里是如何设置收藏夹按钮.从列表瓦片构造函数中,我们可以使用尾部小部件来设置收藏夹按钮const。

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;
        });
      }
热门问题
推荐问题
最新问题