2

what I am doing wrong? even though the function gets called the widget tree isn't updating, another question is how setState knows which widget to rebuild? and is there a way to view the widget tree in runtime?

import 'dart:developer';
import 'package:flutter/material.dart';
import "dart:developer";

class PageOne extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => PageState();
}

class PageState extends State {
  @override
  Widget build(BuildContext context) {
    Color _color = Colors.cyan;
    double _width =300;

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            AnimatedContainer(
              duration: Duration(seconds: 4),
              curve: Curves.fastOutSlowIn,
              width: _width,
              height: 100,
              decoration: BoxDecoration(
                  color: _color, borderRadius: BorderRadius.circular(10)),
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.change_history),
        backgroundColor: Colors.white70,
        onPressed: () {
          setState(() {
            _color = Colors.green;
            _width = 100;
            log("setstate called");
          });
        },
      ),
    );
  }
}
RootOfMinusOne
  • 137
  • 2
  • 11

2 Answers2

2

put color and width above Widget Build:

Color _color = Colors.cyan;
double _width =300;

@override
Widget build(BuildContext context) {
kevinbrink
  • 1,265
  • 8
  • 14
1

You are placing data fields inside build method. So, whenever you called setState() method,the build method is called to rebuild the widget and your updated values in setSate() method are reset to their default values. Therefore, you should place your data fields outside from build method.

class PageState extends State {
   Color _color = Colors.cyan;
   double _width =300;

   @override
   Widget build(BuildContext context) {
   return Scaffold(