我在 flutter 中更改 setState 方法中的值时遇到问题

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

我正在编写一个应用程序,在其主屏幕内我想通过长按单击来选择联系人,它实际上可以工作,但我希望在执行此操作后应用程序栏操作小部件发生变化。所以我创建了一个静态变量,它通过聊天页面中的设置状态方法进行更改,但是当我长按时,这是我的聊天页面代码,它会更改它命名为 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),
                          ),
                        ),
                      )
                    ],
                  );
                }));
  }
}

这是主屏幕代码,应用栏更改应该在此处完成

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(),
        ],
      ),
    );
  }
}

flutter dart setstate
1个回答
0
投票

ChatPage
位于主页内时,您可以向
ChatPage
添加另一个布尔值。要从 ChatPage 更新此布尔值,您可以使用回调方法。

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();
}

现在将

HomeScreen.selected
替换为
widget.isHomeScreenSelected
上的
_ChatPageState
。要更新值请致电

widget.updateHomeScreenSelection(true);

并使用 ChatPage 之类的

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

确保调用 setState 来更新 UI。

© www.soinside.com 2019 - 2024. All rights reserved.