【问题标题】:How to change text in Flutter (Dart)?如何更改 Flutter (Dart) 中的文本?
【发布时间】:2021-11-13 21:37:03
【问题描述】:

我是 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(
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue,
          title: Center(
              child: Text("App demo",
                  style: TextStyle(color: Colors.yellow, fontSize: 40))),
        ),
        body:Center(
          child: Column(children: [
            Text("Hello word !", key: Key("textKey")),
            TextButton(child: Text("change Text"), onPressed: (){
              /* **I want to change "Hello word!" to "Text has changed"** */
              debugPrint("Change");
            },),
          ],),
        )
      ),
    );
  }
}

请教我怎么做? 谢谢大家。

【问题讨论】:

标签: flutter dart text widget


【解决方案1】:

如果要更改文本,则需要使用有状态小部件进行扩展。在无状态中,它无法重建,因此您必须使用有状态的小部件或状态管理,例如(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);

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

class _MyHomePageState extends State<MyHomePage> {
  String helloWorld = "Hello word !";
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.blue,
            title: Center(
                child: Text("App demo",
                    style: TextStyle(color: Colors.yellow, fontSize: 40))),
          ),
          body:Center(
            child: Column(children: [
              Text("$helloWorld", key: Key("textKey")),
              TextButton(child: Text("change Text"), onPressed: (){
                /* **I want to change "Hello word!" to "Text has changed"** */
                debugPrint("Change");
                setState(() {
                  helloWorld = "Change text";

                });
              },),
            ],),
          )
      ),
    );
  }
}

【讨论】:

  • 请把它作为答案,并尝试输入英文,快乐编码!
  • 目前的方法解决了我的问题,但我想问更多我们可以使用“查找小部件”来提出这个请求吗?
  • 您可以使用查找小部件编写测试
猜你喜欢
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
  • 2021-10-24
  • 2020-01-28
  • 2020-03-11
  • 2019-12-18
  • 2023-03-11
  • 2021-12-16
相关资源
最近更新 更多