skip to Main Content

I’m writing an app which inside its home screen I want to select the contacts by long press click it’s actually works but I want after doing this the app bar actions widget change. so I’ve created a static variable which is changing by set state method in chat Page but when I do long press click this is my chat page code which is change the static variable which it has named selected

import 'dart:math';

import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/gestures/long_press.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:whatsapp/Model/ChatModel.dart';
import 'package:whatsapp/Screens/chat/chatScreen.dart';
import 'package:whatsapp/constants/colors.dart';

import '../CustomUI/show_image_fullScreen.dart';
import '../Screens/contacts/select_contact.dart';
import '../Screens/home/HomeScreen.dart';
import '../utils/theme_manager.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key, required this.chatModels}) : super(key: key);
  final List<ChatModel> chatModels;
  
  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  List<Contact>? contacts;

  List<int> selectedIndexList = [];

  LongPressDownDetails? detailPress;

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

  void getAllContacts() async {
    bool isGranted = await Permission.contacts.isGranted;
    if (!isGranted) {
      isGranted = await Permission.contacts.request().isGranted;
    }
    List myContacts = (await ContactsService.getContacts()).toList();
    setState(() {
      contacts = myContacts.cast<Contact>();
    });
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.pushNamed(context, SelectContact.routName);
          },
          child: Icon(Icons.chat, color: Colors.white),
        ),
        body: contacts == null
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : ListView.builder(
                itemCount: contacts!.length,
                itemBuilder: (BuildContext context, index) {
                  int randomNumber = Random().nextInt(colors.length);
                  return Column(
                    children: [
                      const SizedBox(
                        height: 30,
                      ),
                      GestureDetector(
                        onLongPress: () {
                          if (!HomeScreen.selected){
                                setState(() {
                                      HomeScreen.selected = true;
                                      selectedIndexList.add(index);
                                });
                          }
                          else {
                                if (selectedIndexList.contains(index)){
                                      setState(() {
                                            selectedIndexList.remove(index);
                                      });
                                }
                                else {
                                      setState(() {
                                            selectedIndexList.add(index);
                                      });
                                }
                          }
                          if (selectedIndexList.isEmpty){
                                setState(() {
                                      HomeScreen.selected = false;
                                });
                          }

                        },
                        child: ListTile(
                          leading: InkWell(
                              onTap: () {
                                Navigator.push(context,
                                    MaterialPageRoute(builder: (context) {
                                  return ShowImageFullScreen(
                                    sorceChat: widget.chatModels[0],
                                    image: Image.asset("assets/1.jpg"),
                                    tabBarOptions: false,
                                  );
                                }));
                              },
                              child: (contacts![index].avatar == null)
                                  ? CircleAvatar(
                                      backgroundColor: Colors.grey,
                                      radius: 30,
                                      child: SvgPicture.asset(
                                        "assets/person.svg",
                                        color: Colors.grey,
                                        width: 38,
                                        height: 38,
                                      ),
                                    )
                                  : Stack(
                                      children: [
                                        CircleAvatar(
                                          backgroundColor: colors[randomNumber]
                                              ['color'],
                                          radius: 30,
                                          child: Text(
                                            contacts![index].initials(),
                                            style: TextStyle(
                                                color: colors[randomNumber]
                                                            ['mode'] ==
                                                        'light'
                                                    ? Colors.black54
                                                    : Colors.white),
                                          ),
                                        ),
                                        HomeScreen.selected &&
                                                selectedIndexList
                                                    .contains(index)
                                            ? Positioned(
                                                bottom: 0,
                                                right: 0,
                                                child: CircleAvatar(
                                                  backgroundColor:
                                                      ThemeManeger()
                                                              .checkIsDark(
                                                                  context)
                                                          ? tabColor
                                                          : Colors.teal,
                                                  radius: 11,
                                                  child: Container(
                                                    decoration: BoxDecoration(
                                                        border: Border.all(
                                                            color: ThemeManeger()
                                                                    .checkIsDark(
                                                                        context)
                                                                ? Colors.white
                                                                : Colors.black,
                                                            width: 2),
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(11)),
                                                    child: Icon(
                                                      Icons.check,
                                                      color: ThemeManeger()
                                                              .checkIsDark(
                                                                  context)
                                                          ? Colors.white
                                                          : Colors.black,
                                                      size: 18,
                                                    ),
                                                  ),
                                                ),
                                              )
                                            : const Positioned(
                                                child: SizedBox())
                                      ],
                                    )),
                          onTap: () {
                            if (!HomeScreen.selected){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => ChatScreen(
                                    chatModel: widget.chatModels[index],
                                  ),
                                ),
                              );
                            }
                            else {
                              if (selectedIndexList.contains(index)){
                                setState(() {
                                  selectedIndexList.remove(index);
                                });
                              }
                              else {
                                setState(() {
                                  selectedIndexList.add(index);
                                });
                              }
                            }
                            if (selectedIndexList.isEmpty){
                              setState(() {
                                HomeScreen.selected = false;
                              });
                            }
                          },
                          title: Text(
                            contacts![index].displayName!,
                            style: TextStyle(
                                color: ThemeManeger().checkIsDark(context)
                                    ? Colors.white
                                    : Colors.black),
                          ),
                          subtitle: Row(
                            children: [
                              Icon(
                                Icons.done_all,
                                color: ThemeManeger().checkIsDark(context)
                                    ? Colors.white70
                                    : Colors.black45,
                              ),
                              Text(
                                "سلام",
                                style: TextStyle(
                                    color: ThemeManeger().checkIsDark(context)
                                        ? Colors.white70
                                        : Colors.black45),
                              ),
                            ],
                          ),
                          trailing: Text(
                            "3:00",
                            style: TextStyle(
                                color: ThemeManeger().checkIsDark(context)
                                    ? Colors.white70
                                    : Colors.black45,
                                fontSize: 12),
                          ),
                        ),
                      )
                    ],
                  );
                }));
  }
}

and this is the home screen code which the app bar changes should be done in here

import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:theme_provider/theme_provider.dart';
import 'package:whatsapp/Model/ChatModel.dart';
import 'package:whatsapp/constants/colors.dart';
import 'package:whatsapp/pages/ChatPage.dart';
import 'package:whatsapp/pages/StatusPage.dart';

import '../../groups/group.dart';
import '../../pages/CallsPage.dart';
import '../../pages/CommunityPage.dart';
import '../../utils/theme_manager.dart';

class HomeScreen extends StatefulWidget {
  static const String routName = "/Home-screen";
  static bool selected = false;

  const HomeScreen({Key? key, required this.chatModels}) : super(key: key);
  final List<ChatModel> chatModels;
  static int index = 1;

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin {
  TabController? controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller = TabController(length: 4, vsync: this, initialIndex: 1);
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Whatsapp",
          style: TextStyle(
              color: ThemeManeger().checkIsDark(context)
                  ? Colors.grey
                  : Colors.white),
        ),
        actions: [
          HomeScreen.selected == false
              ? Row(
                  children: [
                    IconButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (_) =>
                                ThemeConsumer(child: ThemeDialog()));
                      },
                      icon: Icon(
                        Icons.palette,
                        color: ThemeManeger().checkIsDark(context)
                            ? Colors.grey
                            : Colors.white60,
                      ),
                    ),
                    IconButton(
                        onPressed: () {},
                        icon: Icon(FeatherIcons.camera,
                            color: ThemeManeger().checkIsDark(context)
                                ? Colors.grey
                                : Colors.white70)),
                    IconButton(
                      icon: Icon(
                        Icons.search,
                        color: ThemeManeger().checkIsDark(context)
                            ? Colors.grey
                            : Colors.white70,
                      ),
                      onPressed: () {},
                    ),
                    PopupMenuButton(
                        color: ThemeManeger().checkIsDark(context)
                            ? appBarColor
                            : Colors.white,
                        icon: Icon(Icons.more_vert,
                            color: ThemeManeger().checkIsDark(context)
                                ? Colors.grey
                                : Colors.white),
                        onSelected: (value) {
                          if (value == 0) {
                            Navigator.pushNamed(context, CreateGroup.routName);
                          }
                        },
                        itemBuilder: (BuildContext context) {
                          return [
                            PopupMenuItem(
                              value: 0,
                              child: Text(
                                "New group",
                                style: TextStyle(
                                    color: ThemeManeger().checkIsDark(context)
                                        ? Colors.white
                                        : Colors.black),
                              ),
                            ),
                            PopupMenuItem(
                              child: Text(
                                "New broadcast",
                                style: TextStyle(
                                    color: ThemeManeger().checkIsDark(context)
                                        ? Colors.white
                                        : Colors.black),
                              ),
                            ),
                            PopupMenuItem(
                              child: Text(
                                "Linked devices",
                                style: TextStyle(
                                    color: ThemeManeger().checkIsDark(context)
                                        ? Colors.white
                                        : Colors.black),
                              ),
                            ),
                            PopupMenuItem(
                              child: Text(
                                "Starred messages",
                                style: TextStyle(
                                    color: ThemeManeger().checkIsDark(context)
                                        ? Colors.white
                                        : Colors.black),
                              ),
                            ),
                            PopupMenuItem(
                              child: Text(
                                "Settings",
                                style: TextStyle(
                                    color: ThemeManeger().checkIsDark(context)
                                        ? Colors.white
                                        : Colors.black),
                              ),
                            ),
                          ];
                        })
                  ],
                )
              : Row()
        ],
        bottom: TabBar(
          unselectedLabelColor: ThemeManeger().checkIsDark(context)
              ? Colors.grey
              : Colors.white70,
          labelColor:
              ThemeManeger().checkIsDark(context) ? tabColor : Colors.white,
          indicatorColor:
              ThemeManeger().checkIsDark(context) ? tabColor : Colors.white,
          controller: controller,
          tabs: const [
            Tab(
              icon: Icon(Icons.people),
            ),
            Tab(
              text: "Chats",
            ),
            Tab(
              text: "Status",
            ),
            Tab(
              text: "Calls",
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: controller,
        children: [
          const CommunityPage(),
          ChatPage(
            chatModels: widget.chatModels,
          ),
          const StatusPage(),
          const CallsPage(),
        ],
      ),
    );
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    this is the tab bar view which its return the chat page widget so the parent widget is home screen I have created a static variable in my home screen widget

    TabBarView(
            controller: controller,
            children: [
              const CommunityPage(),
              ChatPage(
                chatModels: widget.chatModels,
              ),
              const StatusPage(),
              const CallsPage(),
            ],
          ),
    
    
    static bool selected = false;
    

    I want to send data from chat page to its parent class which is home screen I'm sure the value of selected value is changing but it needs me a hot reload to update the UI in the app bar if the selected value is true it return some widget else it returns another widget like this :

     AppBar(
    actions: [
    HomeScreen.selected
                ? Row(
    children : [
    // some wigets
      ]
      ): Row()
    ]
    )
    

  2. While the ChatPage is inside the HomePage, you can another bool to the ChatPage. To update this bool from ChatPage, you can use callback method.

    class ChatPage extends StatefulWidget {
      const ChatPage({
        Key? key,
        required this.chatModels,
        required this.isHomeScreenSelected,
        required this.updateHomeScreenSelection,
      }) : super(key: key);
      final List<ChatModel> chatModels;
    
      final bool isHomeScreenSelected;
      final Function(bool) updateHomeScreenSelection;
    
      @override
      State<ChatPage> createState() => _ChatPageState();
    }
    

    Now replace the HomeScreen.selected with widget.isHomeScreenSelected on _ChatPageState. To update the value call

    widget.updateHomeScreenSelection(true);
    

    and Use ChatPage like

    ChatPage(
      chatModels: widget.chatModels,
      isHomeScreenSelected: ,//pass your intial value
      updateHomeScreenSelection: (value) {
        
      },
    ),
    

    Make sure to call setState to update the UI.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search