gpt4 book ai didi

flutter - Stateful Widget 子项未更新

转载 作者:IT王子 更新时间:2023-10-29 06:51:28 24 4
gpt4 key购买 nike

有两个有状态的小部件。MyHomePage 的状态包含计数器。MyHomePage 将内容包装在第二个有状态小部件 SubPage 中。SubPage 有一个子部件,其中包含来自 MyHomePage 的数据。

为了澄清这个问题,子页面内的第一个文本小部件不会在计数器更改时更新。

SubPage 之外的文本小部件按预期递增。

如果我们想要更新内部有状态小部件的内容,我们必须做什么?

我们必须在那里使用有状态的小部件。在实际应用中,这个小部件有一个真实的用例。

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Column(
children: <Widget>[
SubPage(
child: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),

floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

class SubPage extends StatefulWidget {
SubPage({Key key, this.child}) : super(key: key);

final Widget child;

@override
SubPageState createState() => new SubPageState(child);
}

class SubPageState extends State<SubPage> {
final Widget child;

SubPageState(this.child);

@override
Widget build(BuildContext context) {
print("subpage build");
return this.child;
}
}

最佳答案

您不必将 child 设置为状态字段。实际上这是导致此错误的原因。这里是工作代码

class SubPage extends StatefulWidget {
SubPage({Key key, this.child}) : super(key: key);

final Widget child;

@override
SubPageState createState() => new SubPageState();
}

class SubPageState extends State<SubPage> {
@override
Widget build(BuildContext context) {
return widget.child;
}
}

关于flutter - Stateful Widget 子项未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com