Home > Enterprise >  Why does my code not increase the size of the container?
Why does my code not increase the size of the container?

Time:03-17

I am trying to increase the size of the container using GestureDetector's onTap method. But when i tap on the container, nothing happens. I can't figure out what's wrong? Would you suggest me any other way or any package which can produce the same result.

class DemoPage extends StatefulWidget {
  @override
  State<DemoPage> createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  CustomContainer container = CustomContainer();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: GestureDetector(
        onTap: () {
          setState(() {
            container.expandContainer();
          });
        },
        child: container,
      )),
    );
  }
}

class CustomContainer extends StatelessWidget {
  Container _container = Container(
    color: Colors.yellow,
    width: 200.0,
    height: 100.0,
  );

  void expandContainer() {
    //Assignment Operator used with Ternary operator
    _container = _container ==
            Container(
              color: Colors.yellow,
              width: 200.0,
              height: 300.0,
            )
        ? Container(
            color: Colors.yellow,
            width: 200.0,
            height: 100.0,
          )
        : Container(
            color: Colors.yellow,
            width: 200.0,
            height: 300.0,
          );
  }

  @override
  Widget build(BuildContext context) {
    return _container;
  }
}

CodePudding user response:

I prefer using AnimatedContainer for cases like this.

class DemoPage extends StatefulWidget {
  const DemoPage({Key? key}) : super(key: key);

  @override
  State<DemoPage> createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  bool isExanded = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: GestureDetector(
        onTap: () {
          setState(() {
            isExanded = !isExanded;
          });

          print("tapped");
        },
        child: AnimatedContainer(
          color: Colors.yellow,
          width: 200.0,
          height: isExanded ? 300 : 100.0,
          duration: const Duration(seconds: 2),
        ),
      )),
    );
  }
}

  • Related