简体   繁体   English

Flutter:更新其他有状态小部件中的字符串

[英]Flutter: Update String in other statefull widget

I'm using a statefull widget to handle the length of my text.我正在使用一个有状态的小部件来处理我的文本长度。 (show more, show less) (显示更多,显示更少)

class DescriptionTextWidget extends StatefulWidget {
  final String text;

  DescriptionTextWidget({@required this.text});

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

class _DescriptionTextWidgetState extends State<DescriptionTextWidget> {
  String firstHalf;
  String secondHalf;

  bool flag = true;

  @override
  void initState() {
    super.initState();

    if (widget.text.length > 400) {
      firstHalf = widget.text.substring(0, 400);
      secondHalf = widget.text.substring(400, widget.text.length);
    } else {
      firstHalf = widget.text;
      secondHalf = "";
    }
  }


  @override
  Widget build(BuildContext context) {
    return new Container(
      padding: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
      child: secondHalf.isEmpty
          ? new Text(firstHalf, style: TextStyle(color: Colors.white))
          : new Column(
              children: <Widget>[
                new Text(
                  flag ? (firstHalf + "...") : (firstHalf + secondHalf),
                  style: TextStyle(color: Colors.white),
                ),
                new InkWell(
                  splashColor: Colors.transparent,
                  child: new Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      new Text(
                        flag ? "show more" : "show less",
                        style:
                            new TextStyle(color: Colors.white.withOpacity(0.8)),
                      ),
                    ],
                  ),
                  onTap: () {
                    setState(() {
                      flag = !flag;
                    });
                  },
                ),
              ],
            ),
    );
  }
}

In my main class: I 'give' the text to that stfull widget like this:在我的主课中:我将文本“提供”给 stfull 小部件,如下所示:

 GestureDetector(
                    onTap: () async {

                    },
                    child: DescriptionTextWidget(
                        text: myString,
                  ),

If I update myString in my main statefull widget, the String doesn't get updated in the statefull widget 'DescriptionTextWidget'.如果我在主有状态小部件中更新 myString,则字符串不会在有状态小部件“DescriptionTextWidget”中更新。

What's the best way to update the String in the class DescriptionTextWidget?在类 DescriptionTextWidget 中更新字符串的最佳方法是什么?

Thanks in advance!提前致谢!

import 'package:flutter/material.dart';

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

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

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<String> myString = ["test"];

  void _replace() {
    setState(() {
      myString[0] = "tapped";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: DescriptionTextWidget(
          text: myString,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _replace,
        child: Icon(Icons.autorenew),
      ),
    );
  }
}

class DescriptionTextWidget extends StatefulWidget {
  final List<String> text;

  DescriptionTextWidget({@required this.text});

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

class _DescriptionTextWidgetState extends State<DescriptionTextWidget> {
  bool flag = true;

  @override
  Widget build(BuildContext context) {

    String firstHalf;
    String secondHalf;

    if (widget.text[0].length > 400) {
      firstHalf = widget.text[0].substring(0, 400);
      secondHalf = widget.text[0].substring(400, widget.text[0].length);
    } else {
      firstHalf = widget.text[0];
      secondHalf = "";
    }

    return new Container(
      padding: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
      child: secondHalf.isEmpty
          ? new Text(firstHalf, style: TextStyle(color: Colors.black))
          : new Column(
              children: <Widget>[
                new Text(
                  flag ? (firstHalf + "...") : (firstHalf + secondHalf),
                  style: TextStyle(color: Colors.black),
                ),
                new InkWell(
                  splashColor: Colors.transparent,
                  child: new Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      new Text(
                        flag ? "show more" : "show less",
                        style:
                            new TextStyle(color: Colors.black.withOpacity(0.8)),
                      ),
                    ],
                  ),
                  onTap: () {
                    setState(() {
                      flag = !flag;
                    });
                  },
                ),
              ],
            ),
    );
  }
}

Sample on DartPad DartPad 上的示例

class DescriptionTextWidget extends StatefulWidget {
  final ValueNotifier<String> text;
}

class _DescriptionTextWidgetState extends State<DescriptionTextWidget> {
  @override
  void initState() {
    super.initState();
    widget.text.addListener(() => setState(initText));
    initText();
  }

  initText() {
    if (widget.text.value.length > 400) {
      firstHalf = widget.text.value.substring(0, 400);
      secondHalf = widget.text.value.substring(400, widget.text.value.length);
    } else {
      firstHalf = widget.text.value;
      secondHalf = "";
    }
  }
}

main class:主类:

ValueNotifier<String> myString;

updateString(String value){
  myString.value = value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Flutter 中更新我的 ListView 并解决 StateFull Widget 的问题? - How to update my ListView in Flutter and Solve problem with StateFull Widget? 在有状态小部件中按路线名称进行颤动导航 - Flutter navigation by route name in statefull widget Flutter WorkManager 后台获取示例与 StateFull 小部件 - Flutter WorkManager Background Fetch Example With StateFull Widget Flutter:如何共享有状态小部件的实例? - Flutter: How to share an instance of statefull widget? Flutter 状态小部件未更新 svg 图标 - Flutter statefull widget not updating svg icons 如何从 Flutter 中的其他有状态 Class 重建或刷新有状态 Class? - How to Rebuild or Refresh a Statefull Class from an other Statefull Class in Flutter? 如何在 flutter 中将 id 从有状态小部件获取到无状态小部件? - how to get the id from statefull widget to stateless widget in flutter? Flutter:了解无状态/有状态小部件如何布局其子部件? - Flutter: Understanding how does a Stateless/Statefull widget layout its child? Flutter 片段在 statefull 小部件 android studio 中不起作用 - Flutter snippet didn't work in statefull widget android studio 如何在Flutter中正确绑定全状态小部件中的回调函数? - How to bind a callback function in a statefull widget properly in Flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM