flutterdart

Why is onLongPress() not functioning properly?


I am making an app where I have a lot of containers, which are all wrapped in an InkWell(). So far, they are quite simple; when you tap a container it takes you to a new screen. I now want to make the container change color when long pressed. I tested this on a different project, and it worked perfectly. However, when I implement it in my actual code, it doesn't work. The onTap() still works, however, the onLongPress() doesn't execute. The color change never happens when the container is long pressed.

Code:

class ToolsScreen2 extends StatefulWidget {
  ToolsScreen2({super.key});

  @override
  State<ToolsScreen2> createState() => ToolsScreen2State();
}

class ToolsScreen2State extends State<ToolsScreen2> {
  late Color colorContainer = Colors.white24;
  void initState() {
    colorContainer = Color(
      GetStorage().read<int>('colorContainer') ?? Colors.white24.value,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Choose A CLL Case:'),
        iconTheme: const IconThemeData(
          color: Colors.deepOrangeAccent, 
        ),
      ),
      body: ListView(
        children: [
          InkWell(
            onLongPress: () {
              setState(() {
                colorContainer = colorContainer == Colors.white24
                    ? Colors.green.shade600
                    : Colors.white24;
                GetStorage().write('colorContainer', colorContainer.value);
              });
            },  // This is the LongPress that doesn't work.
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const Sune_CLL(),
                ),
              );
            },
            child: Container(
              width: 500,
              color: Colors.white24,
              height: 125,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Image.asset(
                    'images/SuneOrtega BR.png',
                  ),
                  const Padding(
                    padding: EdgeInsets.only(right: 70.0),
                    child: Text(
                      'Sune Cases',
                      style: TextStyle(fontSize: 30),
                    ),
                  ),
                ],
              ),
            ),
          ),

Solution

  • You simply forgot to change the color of the Container() to colorContainer. You need to use the colorContainer you made as the color, not a pre-determined color such as white24.

    So, change this:

    child: Container(
      width: 500,
      color: Colors.white24. <— Change this.
      height: 125, 
    

    To this:

    child: Container(
      width: 500,
      color: colorContainer,<— use colorContainer
      height: 125,