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

问题描述 投票:0回答:1

我需要新手帮助,才能振作起来。我想从函数中获取返回值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
                )
          ],
        ),
      ),
    );
  }
}
flutter flutter-layout
1个回答
0
投票

您可以轻松地使用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)
       ],
     ),
    ),
   );
  }
 }
© www.soinside.com 2019 - 2024. All rights reserved.