如何将函数中的值返回给小部件

时间:2020-03-09 05:36:24

标签: flutter flutter-layout

我需要新的帮助。我想从我的函数中获取返回值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
                )
          ],
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分: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)
       ],
     ),
    ),
   );
  }
 }