Regarding Chat Screen

83 views
Skip to first unread message

HIMANSHU MISHRA

unread,
Jun 16, 2021, 1:35:06 AM6/16/21
to Flutter Development (flutter-dev)
Dear All,

I have attached the ScreenShot Chat Screen of my App. Now I want to Add Feature of WhatsApp(Grouping of Messages according to Date). In this App I have used Buuble Package. Everything is working fine. I have also attached the code as well.

Now please guide me to do add Date Wise Chat Messages on Screen Like WhatsApp.
If there is any plugin please let me know

import 'dart:convert';
import 'package:conqer_music/App/Model/APIUrl.dart';
import 'package:conqer_music/App/Model/PrayerData.dart';
import 'package:http/http.dart' as http;
import 'package:conqer_music/App/Model/User.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:bubble/bubble.dart';
import 'package:date_format/date_format.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:swipe_to/swipe_to.dart';

class PrayerLinePage extends StatefulWidget {
  static const String routeName = '/prayerLinePage';
  @override
  _PrayerLinePageState createState() => _PrayerLinePageState();
}

class _PrayerLinePageState extends State<PrayerLinePage> {
  TextEditingController messageController = TextEditingController();
  late FocusNode messageFocus;
  String apiURL = APIUrl().stagingURl;
  String isAnonymous = '';
  String userID = '';
  String userFullName = '';
  bool anonymous = false;
  String userProfilePic = '';
  @override
  void initState() {
    super.initState();
    readData();
  }

  readData() async {
    final prefs = await SharedPreferences.getInstance();
    final userId = prefs.getString('userId') ?? '';
    final userName = prefs.getString('userName') ?? '';
    final userPic = prefs.getString('userPic') ?? '';

    setState(() {
      userID = userId;
      userFullName = userName;
      userProfilePic = userPic;
    });
  }

  Future<List<PrayerData>> prayerList() async {
    const String apiURL = 'https://staging.conqermusic.com/api/prayer-list.php';

    final response = await http.get(Uri.parse(apiURL));
    if (response.statusCode == 200) {
      Map data = jsonDecode(response.body); //Yahan Data Aa Rha Hai
      List apiData = data['res_data'];
      print(apiData);
      return apiData.map((e) => new PrayerData.fromJson(e)).toList();
    } else {
      throw Exception('Failed to load data from API');
    }
  }

  Future<UsersendPrayerRequest() async {
    onLoading();
    // String uID = userID;
    String userMessage = messageController.text.trim();
    print('IsAnony ' + isAnonymous);
    final response = await http.post(
      headers: <StringString>{
        'Content-Type''application/json; charset=UTF-8',
      },
      bodyjsonEncode(<StringString>{
        'user_id'userID,
        'anonymus'isAnonymous,
        'message'userMessage,
      }),
    );
    if (response.statusCode == 200) {
      Navigator.pop(context);
      setState(() {
        Map data = jsonDecode(response.body);
        String resStatus = data['res_status'];

        print(resStatus);
        if (resStatus == '200') {
        } else {
          // showUpdateProfileFailed(context);
        }
      });

      return User.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Login Failed...');
    }
  }

  showMessageTextFieldAlert(BuildContext context) {
    // Create button
    // ignore: deprecated_member_use
    Widget okButton = FlatButton(
      childText("OK"),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );

    // Create AlertDialog
    AlertDialog alert = AlertDialog(
      contentText("Please Enter the Message"),
      actions: [
        okButton,
      ],
    );

    // show the dialog
    showDialog(
      contextcontext,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

  onLoading() {
    showDialog(
      contextcontext,
      barrierDismissiblefalse,
      builder: (BuildContext context) {
        return Center(
          childContainer(
            height50,
            width50,
            childnew Row(
              mainAxisAlignmentMainAxisAlignment.center,
              children: [
                new CircularProgressIndicator(
                  backgroundColorColor(0xFFbaa15e),
                ),
                // new Text("Loading..."),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final screenWidgth = MediaQuery.of(context).size.height;

    Widget sendMessage() {
      return Container(
        childColumn(
          children: [
            Container(
              paddingEdgeInsets.only(top10),
              widthscreenWidgth * 0.6,
              childTextFormField(
                textInputActionTextInputAction.next,
                controllermessageController,
                decorationInputDecoration(
                  isDensetrue,
                  hintText'Prayer Request',
                  contentPaddingEdgeInsets.fromLTRB(100100),
                  filledtrue,
                  suffixStyleTextStyle(
                      fontSize14,
                      fontWeightFontWeight.bold,
                      colorColors.white),
                  fillColorColor(0xFFbaa15e),
                  hintStyleTextStyle(
                    colorColors.white,
                  ),
                  suffixIconIconButton(
                      tooltip'Send Request',
                      iconIcon(Icons.play_circle_outline_sharp),
                      colorColors.white,
                      iconSize30,
                      onPressed: () {
                        if (messageController.text == '') {
                          showMessageTextFieldAlert(context);
                        } else {
                          sendPrayerRequest();
                          FocusScopeNode currentFocus = FocusScope.of(context);

                          if (!currentFocus.hasPrimaryFocus) {
                            currentFocus.unfocus();
                            messageController.clear();
                          }
                        }
                      }),
                  borderOutlineInputBorder(
                    borderRadiusBorderRadius.circular(20.0),
                  ),
                ),
                styleTextStyle(
                    colorColors.white,
                    fontSize14,
                    textBaselineTextBaseline.alphabetic),
              ),
            ),
            Row(
              children: [
                Expanded(
                    flex0,
                    childCheckbox(
                      checkColorColors.black,
                      activeColorColors.white,
                      valueanonymous,
                      onChanged: (value) {
                        setState(() {
                          anonymous = value!;
                          if (anonymous.toString() == 'false') {
                            isAnonymous = '0';
                          } else {
                            isAnonymous = '1';
                          }
                        });
                      },
                    )

                    // RoundCheckBox(
                    //   onTap: (selected) {
                    //     setState(() {
                    //       if (anonymous == '0') {
                    //         anonymous = '1';
                    //       } else {
                    //         anonymous = '0';
                    //       }
                    //     });
                    //   },
                    //   size: 14,
                    //   uncheckedColor: Colors.white,
                    //   checkedColor: Colors.black,
                    // ),
                    //  Radio(
                    //     focusColor: Colors.black,
                    //     value: 0,
                    //     groupValue: anonymous,
                    //     // activeColor: Color(0xFF6200EE),
                    //     onChanged: (var x) {
                    //       setState(() {
                    //         x = '1';
                    //         anonymous = x.toString();
                    //       });
                    //     })
                    ),
                Expanded(
                    flex1,
                    childText(
                      'Anonymous',
                      styleTextStyle(colorColors.white),
                    )),
              ],
            ),
          ],
        ),
      );
    }

    Widget prayerListData(String idString nameString message,
        String anonymousString userpicString msgdate) {
      DateTime msgdt = DateTime.parse(msgdate);
      // final msgDateTime =
      //     formatDate(msgdt, [mm, '-', dd, '-', yy, ' ', HH, ':', mm]);
      String msgDateTime = DateFormat(' hh:mm a').format(msgdt);

      if (id.toString() == userID) {
        return SingleChildScrollView(
          childContainer(
            childRow(
              mainAxisAlignmentMainAxisAlignment.start,
              children: <Widget>[
                anonymous == '0'
                    ? CircleAvatar(
                        backgroundImageNetworkImage(
                          apiURL + userpic.substring(2),
                        ),
                        backgroundColorColors.transparent,
                        radius22.0,
                      )
                    : CircleAvatar(
                        backgroundImageAssetImage(
                          'lib/App/Assets/Images/Anonymous.png',
                        ),
                        backgroundColorColors.transparent,
                        radius22.0,
                      ),
                SizedBox(
                  width5,
                ),
                SwipeTo(
                  onRightSwipe: () {},
                  childBubble(
                    // alignment: Alignment.topLeft,
                    radiusRadius.elliptical(5.08.0),
                    paddingBubbleEdges.all(5),
                    nipid.toString() == userID
                        ? BubbleNip.leftTop
                        : BubbleNip.rightTop//  nip: BubbleNip.rightBottom,
                    colorid.toString() == userID
                        ? Color(0xFFbaa15e)
                        : Colors.white,
                    childText(
                      message + '  ' + msgDateTime,
                      textAlignTextAlign.justify,
                      maxLines3,
                      overflowTextOverflow.ellipsis,
                      styleTextStyle(
                          color: (id.toString() == userID
                              ? Colors.white
                              : Color(0xFFbaa15e)),
                          fontSize10),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        return SingleChildScrollView(
          childContainer(
            widthscreenWidgth,
            childRow(
              mainAxisAlignmentMainAxisAlignment.end,
              // crossAxisAlignment: id.toString() == userID
              //     ? CrossAxisAlignment.end
              //     : CrossAxisAlignment.start,
              children: <Widget>[
                // SizedBox(
                //   width: 10,
                // ),
                SwipeTo(
                  onRightSwipe: () => {},
                  childBubble(
                    //  margin: BubbleEdges.only(top: 8, left: 50),
                    alignmentAlignment.topRight,
                    radiusRadius.elliptical(5.08.0),
                    paddingBubbleEdges.all(5),
                    nipid.toString() == userID
                        ? BubbleNip.leftTop
                        : BubbleNip.rightTop//  nip: BubbleNip.rightBottom,
                    colorid.toString() == userID
                        ? Color(0xFFbaa15e)
                        : Colors.white,
                    childWrap(
                      directionAxis.horizontal,
                      children: [
                        Text(
                          'Ive been having a problem with my computer. Please see it. I am very tensed. I have a lot of work to do...',
                          //  message + '  ' + msgDateTime,
                          maxLines3,
                          textAlignTextAlign.justify,
                          overflowTextOverflow.ellipsis,
                          softWraptrue,
                          styleTextStyle(
                              color: (id.toString() == userID
                                  ? Colors.white
                                  : Color(0xFFbaa15e)),
                              fontSize10),
                        ),
                        // SizedBox(
                        //   height: 5,
                        // ),
                        // Align(
                        //   alignment: Alignment.bottomRight,
                        //   child: Text(
                        //     msgDateTime,
                        //     style: TextStyle(
                        //         fontSize: 9,
                        //         color: (id.toString() == userID
                        //             ? Colors.white
                        //             : Color(0xFFbaa15e))),
                        //   ),
                        // )
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  width5,
                ),
                anonymous == '0'
                    ? CircleAvatar(
                        backgroundImageNetworkImage(
                          apiURL + userpic.substring(2),
                        ),
                        backgroundColorColors.transparent,
                        radius22.0,
                      )
                    : CircleAvatar(
                        backgroundImageAssetImage(
                          'lib/App/Assets/Images/Anonymous.png',
                        ),
                        backgroundColorColors.transparent,
                        radius22.0,
                      ),
              ],
            ),
          ),
        );
      }
    }

    showNetworkAlert(BuildContext context) {
      // Create button
      // ignore: deprecated_member_use
      Widget okButton = FlatButton(
        childText("OK"),
        onPressed: () {
          Navigator.of(context).pop();
        },
      );

      // Create AlertDialog
      AlertDialog alert = AlertDialog(
        titleText("Alert"),
        contentText("Please check the network"),
        actions: [
          okButton,
        ],
      );

      // show the dialog
      showDialog(
        contextcontext,
        builder: (BuildContext context) {
          return alert;
        },
      );
    }

    ListView prayerData(List<PrayerDatadata) {
      return ListView.builder(
        physicsBouncingScrollPhysics(),
        shrinkWraptrue,
        paddingEdgeInsets.only(top10bottom10),
        itemCountdata.length,
        itemBuilder: (contextindex) {
          return prayerListData(
              data[index].userid,
              data[index].username,
              data[index].message,
              data[index].anonymus,
              data[index].userpic,
              data[index].msgdate);
        },
      );
    }

    return Scaffold(
      resizeToAvoidBottomInsettrue,
      bodyContainer(
        heightscreenHeight * 1.3,
        widthscreenWidgth,
        childColumn(
          children: [
            sendMessage(),
            Expanded(
              childFutureBuilder<List<PrayerData>>(
                futureprayerList(),
                builder: (contextAsyncSnapshot snapshot) {
                  if (snapshot.hasData) {
                    List<PrayerDatadata = snapshot.data;
                    return prayerData(data);
                  } else if (snapshot.hasError) {
                    return Container(
                      childshowNetworkAlert(context),
                    );
                  }
                  return Center(
                      childContainer(
                          height50,
                          width50,
                          childCircularProgressIndicator()));
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

.
Screenshot_2021-06-16-10-59-29-609_com.hashtag.Conqer.jpg


--
Thanks and Regards
HIMANSHU MISHRA

Benedicte Roussel

unread,
Jun 16, 2021, 6:28:46 AM6/16/21
to HIMANSHU MISHRA, Flutter Development (flutter-dev)
DateTime ... timestamp


Le mer., juin 16, 2021 à 7:35, HIMANSHU MISHRA
--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/CAJySXU-NW%3DqaCEA-6cP2qqt0hVgCpS9aTFtLp0R3pCaLtFV8Yw%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages