我是Flutter的新手! 我想在點擊按鈕 "改變文本 "時改變 "文本 "的內容。 請看下面的代碼:
void main() {
runApp(MaterialApp(home: MyHomePage())。
}
class MyHomePage extends StatelessWidget{
const MyHomePage({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
孩子。Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
標題。中心(
孩子。Text("App demo",
風格。TextStyle(color: Colors.yellow, fontSize: 40) )。
),
body:Center(
孩子。Column(children: [
Text("Hello word!", key: key("textKey"))。
TextButton(child: Text("change Text"), onPressed: (){
/* **我想把 "Hello word!"改為 "Text has changed "** */
debugPrint("Change"/span>)。
},),
],),
)
),
);
}
}
uj5u.com熱心網友回復:
如果你想改變文本,你需要用一個有狀態的小部件來擴展。在無狀態下,它不能重建,所以你必須使用有狀態的部件或狀態管理,如(bloc, provider, getx等)
import 'package:flutter/material.dart'。
void main() {
runApp(MaterialApp(home: MyHomePage())。
}
class MyHomePage extends StatefulWidget{
const MyHomePage({
Key key,
}) : super(key: key);
_MyHomePageState createState() => _MyHomePageState()。
}
class _MyHomePageState extends State< MyHomePage> {
String helloWorld = "Hello word!";
Widget build(BuildContext context) {
return SafeArea(
孩子。Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
標題。中心(
孩子。Text("App demo",
風格。TextStyle(color: Colors.yellow, fontSize: 40) )。
),
body:Center(
孩子。Column(children: [
Text("$helloWorld"/span>, key: Key("textKey"))。
TextButton(child: Text("change Text"), onPressed: (){
/* **我想把 "Hello word!"改為 "Text has changed "** */
debugPrint("Change")。
setState(() {
helloWorld = "更改文本"。
});
},),
],),
)
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/329167.html
標籤:
上一篇:如何使用crossAxisAlignmentFlutter對準行中的小部件
下一篇:mysql規則配置

