当我单击“按钮”时,就像所有帖子一样,我只想一个帖子告诉我如何才能只喜欢一个帖子

时间:2019-06-25 12:41:23

标签: flutter flutter-layout

我只想当我单击“赞”按钮时,就像只有一篇帖子一样,请帮助我如何实现此功能,例如“赞”按钮谢谢。

import 'package:assort_project/preferences.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:share/share.dart';
import 'browser.dart';
import 'home_screen.dart';
import 'package:timeago/timeago.dart' as timeago;

class NewsFeedPage extends StatefulWidget {
  @override
  _NewsFeeds createState() => _NewsFeeds();
}

class _NewsFeeds extends State<NewsFeedPage> {
  String _id;

  bool liked = false;
  var date = new DateTime.fromMillisecondsSinceEpoch(1561092817 * 1000);
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
      new GlobalKey<RefreshIndicatorState>();

  void getData() {
    FirebaseDatabase.instance
        .reference()
        .child("NewsFeed")
        .once()
        .then((DataSnapshot snapshot) {
      Map<dynamic, dynamic> values = snapshot.value;
      values.forEach((key, values) {
        print(values["country"]);
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    getData();
    getCurrentUser();
    print(getCurrentUser());
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('News Feed'),
        ),
        drawer: new Drawer(
          child: Container(
              alignment: Alignment.center,
              child: new Column(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(bottom: 10, right: 5, top: 25),
                    alignment: Alignment.center,
                    color: Color(0xffF7F7F7),
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'assets/images/defalut.png',
                          height: 100,
                          width: 100,
                        ),
                        SizedBox(
                          height: 15.0,
                        ),
                        Container(
                          alignment: Alignment.topRight,
                          child: Row(
                            // Replace with a Row for horizontal icon + text
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Icon(Icons.border_color),
                              SizedBox(
                                width: 10.0,
                              ),
                              Text(
                                "Edit Profile",
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 15.0,
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.all(20),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        SizedBox(
                          height: 15.0,
                        ),
                        Row(
                          // Replace with a Row for horizontal icon + text
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Icon(Icons.radio),
                            SizedBox(
                              width: 10.0,
                            ),
                            Text(
                              "News Feed",
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 15.0,
                              ),
                            )
                          ],
                        ),
                        SizedBox(
                          height: 15.0,
                        ),
                        InkWell(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => UserBirthBasisPage()),
                            );
                          },
                          child: Row(
                            // Replace with a Row for horizontal icon + text
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Icon(Icons.settings),
                              SizedBox(
                                width: 10.0,
                              ),
                              Text(
                                "Preferences",
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 15.0,
                                ),
                              )
                            ],
                          ),
                        ),
                        SizedBox(
                          height: 15.0,
                        ),
                        Row(
                          // Replace with a Row for horizontal icon + text
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Icon(Icons.favorite_border),
                            SizedBox(
                              width: 10.0,
                            ),
                            Text(
                              "Favorite",
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 15.0,
                              ),
                            )
                          ],
                        ),
                        SizedBox(
                          height: 15.0,
                        ),
                        Row(
                          // Replace with a Row for horizontal icon + text
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Icon(Icons.announcement),
                            SizedBox(
                              width: 10.0,
                            ),
                            Text(
                              "About us",
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 15.0,
                              ),
                            )
                          ],
                        ),
                        SizedBox(
                          height: 15.0,
                        ),
                        InkWell(
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => new LoginScreen()),
                            );
                          },
                          child: Row(
                            // Replace with a Row for horizontal icon + text
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Icon(Icons.exit_to_app),
                              SizedBox(
                                width: 10.0,
                              ),
                              Text(
                                "Logout",
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 15.0,
                                ),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              )),
        ),
        backgroundColor: Color(0xffF7F7F7),
        body: StreamBuilder(
            stream:
                FirebaseDatabase.instance.reference().child("NewsFeed").onValue,
            builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
              if (snapshot.hasData) {
                Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
                map.forEach((dynamic, v) => print(v["imageUrl"]));
                return ListView.builder(
                  itemCount: map.values.toList().length,
                  itemBuilder: (context, index) {
                    return nameDropDownList1(
                      map,
                      index,
                    );
                  },
                );
              } else {
                return Center(child: CircularProgressIndicator());
              }
            }));
  }

  Future<String> getCurrentUser() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    _id = user.uid.toString();
    return user.uid.toString();
  }

  Future<void> signOut() async {
    return FirebaseAuth.instance.signOut();
  }

  void _likePressed() {
    setState(() {
      liked = !liked;
    });
  }

  Widget nameDropDownList1(Map map, int index) {
    return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Flexible(
        child: Card(
          child: new InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ContactUsPage(
                        map.values.toList()[index]["articleUrl"])),
              );
            },
            child: new Padding(
              padding: const EdgeInsets.all(4.0),
              child: new Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Flexible(
                    child: Container(
                      alignment: Alignment.topCenter,
                      width: double.infinity,
                      height: 250,
                      child: Image.network(
                        map.values.toList()[index]["imageUrl"],
                        width: double.infinity,
                        height: 300,
                        fit: BoxFit.cover,
                      ),
                    ),
                    fit: FlexFit.loose,
                    flex: 7,
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  new Flexible(
                    child: Text(
                      map.values.toList()[index]["articleTitle"],
                      textAlign: TextAlign.left,
                      style: TextStyle(
                          fontSize: 16,
                          color: Colors.blue,
                          fontWeight: FontWeight.bold),
                      maxLines: 2,
                    ),
                    flex: 2,
                    fit: FlexFit.loose,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  new Flexible(
                    child: Text(
                      map.values.toList()[index]["content"],
                      style: TextStyle(
                        fontSize: 15,
                        color: Colors.black54,
                      ),
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                    ),
                    flex: 2,
                    fit: FlexFit.loose,
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  new Flexible(
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: Text(
                        timeago.format(DateTime.fromMillisecondsSinceEpoch(
                            map.values.toList()[index]["timeStamp"] * 1000)),
                        style: TextStyle(
                          fontSize: 15,
                          color: Colors.black,
                        ),
                        textAlign: TextAlign.right,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ),
                    flex: 1,
                    fit: FlexFit.loose,
                  ),
                  Flexible(
                    child: new Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        IconButton(
                              icon: Icon(
                                liked ? Icons.favorite : Icons.favorite_border,
                                color: liked ? Colors.red : Colors.black,
                              ),
                              onPressed: () {

                              }),
                        IconButton(
                            icon: Icon(
                              Icons.comment,
                            ),
                            onPressed: () {}),
                        IconButton(
                            icon: Icon(
                              Icons.star_border,
                            ),
                            onPressed: () {
                              FirebaseDatabase.instance
                                  .reference()
                                  .child('UserFavouritPoste')
                                  .child(_id)
                                  .push()
                                  .set({
                                'newsFeedId': map.values.toList()[index]
                                    ["NewsFeedId"],
                              });
                            }),
                        IconButton(
                            icon: Icon(
                              Icons.share,
                            ),
                            onPressed: () {
                              Share.share('check out ' +
                                  map.values.toList()[index]["articleUrl"]);
                            }),
                      ],
                    ),
                    fit: FlexFit.loose,
                    flex: 2,
                  ),
                ],
              ),
            ),
          ),
        ),
        fit: FlexFit.loose,
        flex: 1,
      ),
    ]);
  }
}

我被困在那里,我们将不胜感激任何帮助或建议。提前致谢。

1 个答案:

答案 0 :(得分:0)

您需要将帖子分成单独的小部件。设置后,更改liked属性,该属性对于您正在构建的所有卡都是相同的,这就是所有帖子都被喜欢的原因。如果您将每个帖子都作为单独的小部件,则每个帖子将具有不同的状态。

示例:

return ListView.builder(
                  itemCount: map.values.toList().length,
                  itemBuilder: (context, index) {
                    return PostWidget();
                   },
       );

发布小部件:

class PostWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _PostWidgetState();
  }
}

class _PostWidgetState extends State<PostWidget> {
  bool _liked = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
           onTap: () {
             setState(() { _liked = !_liked; });
            },
           child: Container(
            color: Colors.red,
           ),
);
  }
}