ParentPage:
class ParentPage extends StatefulWidget {
@override
ParentPageState createState() => ParentPageState()。
}
class ParentPageState< T extends ParentPage> extends State<T> {
int counter = 0;
void incrementCounter() => setState(() => counter ) 。
@override
Widget build(BuildContext context) => Text('$counter'); // Not updating
}
ChildPage:
class ChildPage extends ParentPage {
@override
_ChildPageState createState() => _ChildPageState()。
}
class _ChildPageState extends ParentPageState< ChildPage> {
@override。
Widget build(BuildContext context) {
print('build[$counter]'); //更新
return Scaffold(
體。ParentPage(),
floatingActionButton: FloatingActionButton()
onPressed: incrementCounter,
孩子。Icon(Icons.add),
),
);
}
}
我正在使用home.ChildPage()在我的MaterialApp widget中。ChildPage()在我的MaterialApp widget中。
問題:
當我點擊FAB時,它增加了counter(可以在_ChildPageState.build方法的列印陳述句中看到),但ParentPage中的Text部件卻停留在0。為什么會這樣呢?
uj5u.com熱心網友回復:
當建立ChildPage時,你創建了一個新的ParentPage的實體。
body: ParentPage()。
這是一個單獨的實體,所以它有自己的狀態。
只是如果你有兩個不同的容器--你不會期望它們擁有相同的屬性,只是因為它們使用相同的類。
你可以通過檢查子部件中counter的值來測驗它。
class ChildPage extends ParentPage {
@override
_ChildPageState createState() => _ChildPageState()。
}
class _ChildPageState extends ParentPageState< ChildPage> {
@override。
Widget build(BuildContext context) {
print('build[$counter]'); //更新
return Scaffold(
體。Column(children: [ParentPage(), Text('$counter',])。
floatingActionButton。FloatingActionButton(
onPressed: incrementCounter,
孩子。Icon(Icons.add),
),
);
}
}
uj5u.com熱心網友回復:
它保持在0,因為你正在做的對setState()的呼叫將更新_ChildPageState的狀態而不是你的body的狀態。ParentPage()的狀態,因為它是一個不同的實體。
同樣,你的print('build[$counter]');它將顯示正確的值,因為它是你的_ChildPageState的counter變數,而不是你的ParentPage()中的那個。
uj5u.com熱心網友回復:
請嘗試使用自定義小部件
上級頁面:import 'package:flutter/material.dart'。
class ParentPage extends StatefulWidget{
@override
ParentPageState createState() => ParentPageState();
}
class ParentPageState< T extends ParentPage> extends State<T> {
int counter = 0;
void incrementCounter() => setState(() => counter ) 。
body() {
return Center(child: Text('$counter')。
}
@override; }
Widget build(BuildContext context) => body();
}
子頁面:
import 'package:flutter/material.dart'。
import 'package:so_test/model/list_model.dart'。
class ChildPage extends ParentPage {
@override
_ChildPageState createState() => _ChildPageState()。
}
class _ChildPageState extends ParentPageState < ChildPage> {
@override>
body() {
return Scaffold(
身體。Center(child: Text("$counter"),) 。
floatingActionButton。FloatingActionButton(
onPressed: incrementCounter,
孩子。Icon(Icons.add)。
),
);
}
}
因此,這基本上意味著 build() 方法中的 BuildContext 實際上是它的父方法。因此,他們沒有必要明確地傳遞它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313110.html
標籤:
上一篇:試圖從void/string顯示文本,得到"Closure:(dynamic)=>voidfromFunction?
