【问题标题】:How to return value in function to widget如何将函数中的值返回到小部件
【发布时间】:2020-06-21 00:37:42
【问题描述】:

我需要帮助,我是新来的 Flutter。我想从我的函数中获取返回值 String 并在我的 Text Widget 中获取它。那不是我真正的代码,但我希望它像那样工作。而且每次我按下按钮时,文本小部件上的字符串值也会发生变化。谢谢

String textReturn(String value){
  String text = "value";
  return text.toString();
}


class SamplePage extends StatefulWidget {
  @override
  _SamplePageState createState() => _SamplePageState();
}

class _SamplePageState extends State<SamplePage> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: (){
                textReturn("This is the value");
                }, 
              child: Text("Button")
              ),
              Text(
                textReturn
                )
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

  • 使用 setState(() {someStringVariable = textReturn("This is the value");});Text(someStringVariable) 但实际上你不需要 textReturn - 只需使用 setState(() {someStringVariable = "This is the value";});setState(() =&gt; someStringVariable = "This is the value");
  • @pskink 我认为这应该是答案
  • @epsilon 所以把它写成一个自我回答

标签: flutter flutter-layout


【解决方案1】:

您可以使用state 轻松完成此操作,并且您将不再需要函数的返回值,因为设置状态会导致 UI 重新呈现并反映屏幕中值的更改。解决方法如下:

import 'package:flutter/material.dart';

class SamplePage extends StatefulWidget {
 SamplePage();

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

class _SamplePageState extends State<SamplePage> {
String _sampleString;

void textReturn(String value) {
  String text = "value";

  setState(() {
   _sampleString = text;
  });
}

@override
Widget build(BuildContext context) {
 return Center(
   child: Container(
     child: Column(
       children: <Widget>[
         FlatButton(
           onPressed: () {
             textReturn("This is the value");
           },
           child: Text("Button"),
         ),
         Text(this._sampleString)
       ],
     ),
    ),
   );
  }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多