简体   繁体   English

如何使用 onPressed 为选择的最喜欢的图标选择单个颤动 ListTiles?

[英]How do I select individual flutter ListTiles for a select favorite icon with onPressed?

Here is the entire code that I can't add user favorite list to.这是我无法向其中添加用户收藏夹列表的整个代码。 I simply want the heart icon to change color when selected as favorite, then push the saved favorite item to a saved favorites page.我只是想让心形图标在被选为收藏时改变颜色,然后将保存的收藏项推送到保存的收藏页面。

I have no idea what else to do, since I must use itemLength.我不知道还能做什么,因为我必须使用 itemLength。 It is not appearing to be possible with streambuilder. streambuilder 似乎不可能。

class Books extends StatefulWidget {
@override
_BooksState createState() => _BooksState();
}

class _BooksState extends State<Books> {
var firestoreDb = Firestore.instance.collection("books").snapshots();


static final int _itemLength = snapshot.data.documents[index]['title'].length;
List<bool> _isFavorited = List<bool>.generate(_itemLength, (_) => false);


@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Book List',
                style: GoogleFonts.lato(
                  fontSize: 22.0,
                  color: Colors.amberAccent.shade50,
                ),
              )),
          IconButton(
            icon: Icon(MdiIcons.gift, color: Color(0xffffe0b2), size: 32.0),
            onPressed: () {
              _launchURL();
            },
          ),
        ]),
    backgroundColor: Colors.lightBlue,
    elevation: 50.0,
  ), //AppBar

  body: Container(
    width: MediaQuery.of(context).size.width,
    child: StreamBuilder(
        stream: firestoreDb,
        builder: (context, snapshot) {
          if (!snapshot.hasData) Text('Loading...');
          return StaggeredGridView.countBuilder(
            crossAxisCount: 2,
            mainAxisSpacing: 1.0,
            crossAxisSpacing: 1.0,
            padding: EdgeInsets.symmetric(horizontal: 2.0, vertical: 6.0),
            shrinkWrap: true,
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, int index) => Container(
              child: Column(
                children: <Widget>[
                  Card(
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.0),
                    ),

                    child: Column(children: <Widget>[
                      ListTile(
                        title: Text(
                          '${(snapshot.data.documents[index]['title'])}',
                          style: GoogleFonts.lato(
                            fontSize: 20.0,
                            height: 1.2,
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.center,
                        ),

                        subtitle: Row(
                            mainAxisSize: MainAxisSize.max,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Expanded(
                                child: IconButton(
                                  icon: Icon(
                                    Icons.share,
                                    color: Colors.amberAccent,
                                  ),
                                  onPressed: () => Share.share(
                                    '${(snapshot.data.documents[index]['title'])}',
                                  ),
                                ),
                              ),

                              Expanded(
                                child: IconButton(
                                  onPressed: () => setState(() =>
                                  _isFavorited[index] =
                                  !_isFavorited[index]),
                                  icon: _isFavorited[index]
                                      ? Icon(MdiIcons.heart,color: Colors.red)
                                      : Icon(MdiIcons.heartOutline,color: Colors.red,),
                                ),
                              ),

                              Expanded(
                                child: Text(
                                  '${(snapshot.data.documents[index]['subtitle'])}',
                                  textAlign: TextAlign.right,
                                  style: GoogleFonts.lato(
                                    fontSize: 13.0,
                                    fontWeight: FontWeight.w900,
                                    fontStyle: FontStyle.italic,
                                    color: Colors.blue,
                                  ),
                                ), //subtitle: Text
                              ),
                            ] //children
                        ), //Row
                      ), //listtile
                    ]),
                  ),
                ],
              ),
            ),
            staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
          );
        }),
  ),
);
} //build
} //class

_launchURL() async {
const url = 'https://amazon.com';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

You've to maintain the value of _isFavorited for all the ListTiles .您必须为所有ListTiles维护_isFavorited的值。 So bool _isFavorited should be List<bool> _isFavorited .所以bool _isFavorited应该是List<bool> _isFavorited Then you can modify the IconButton's logic as follows:然后你可以修改 IconButton 的逻辑如下:

Expanded(
    child: IconButton(
        icon: _isFavorited[index]
            ? Icon(Icons.star)
            : Icon(Icons.star_border),                     
        onPressed: () => setState(() => _isFavorited[index] = !_isFavorited[index]),
    ), 
),

I've created a sample demo for this on DartPad我在DartPad为此创建了一个示例演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM