1

我做错了什么?即使该函数被调用,小部件树也没有更新,另一个问题是 setState 如何知道要重建哪个小部件?有没有办法在运行时查看小部件树?

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");
          });
        },
      ),
    );
  }
}
4

2 回答 2

1

将颜色和宽度放在 Widget Build 上方:

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

@override
Widget build(BuildContext context) {
于 2019-08-14T21:29:52.820 回答
0

您将数据字段放在构建方法中。因此,每当您调用 setState() 方法时,都会调用 build 方法来重建小部件,并且 setSate() 方法中的更新值将重置为其默认值。因此,您应该将数据字段放在构建方法之外。

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

   @override
   Widget build(BuildContext context) {
   return Scaffold(
于 2019-08-15T14:47:53.863 回答