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