如何将变量放入Flutter中的文本?

bt1cpqcv  于 2022-12-14  发布在  Flutter
关注(0)|答案(4)|浏览(259)

新手的简单问题。我想将回调创建的变量的结果保存为var,并将其输出到另一个小部件的文本中。我该怎么做...?

Row(
                        children: [
                          Expanded(
                            child: Container(
                              height: 40,
                              color: primaryColor20,
                              child: Text(''),
                            ),
                          ),
                          ElevatedButton(
                            onPressed: () async {
                              await Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (_) => KpostalView(
                                    callback: (Kpostal result){
                                      print(result.address);
                                      var resultAddress = result.address;
                                    },
                                  ),
                                ),
                              );
                            },
                            child: Text('Find Address'),
                          ),
                        ],
                      ),

7bsow1i6

7bsow1i61#

使用StatefulWidget,那么setState(() => resultAddress = result.address;这样的税就可以使用Text(resultAddress)

gg58donl

gg58donl2#

您必须使用StatefulWidget

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  String resultAddress = ""; //This is the variable that you will use in the expanded
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 40,
            color: primaryColor20,
            child: resultAddress, //Here is where you use it
          ),
        ),
        ElevatedButton(
          onPressed: () async {
            await Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => KpostalView(
                  callback: (Kpostal result) {
                    print(result.address);
                    setState(() {
                      //You have to use the set state to rebuild the widget with the new state
                      resultAddress = result.address;
                    });
                  },
                ),
              ),
            );
          },
          child: Text('Find Address'),
        ),
      ],
    );
  }
}
oalqel3c

oalqel3c3#

您可以使用Text('My text ${result.address}'),但要刷新该值,您需要将其置于StatefulWidget中

f8rj6qna

f8rj6qna4#

你有两个选择。
1.通过使用setState(() => resultAddress = result.address;来使用StatefullWidget这使得可以通过使用setState来改变resultAddress
1.使用Provider之类的状态管理。创建一个类,如下所示:

import 'package:flutter/material.dart';

class AddressProvider extends ChangeNotifier {
  String? _resultAddress;

  String? get resultAddress => _resultAddress;

  void setResultAddress(String? newResultAddress) {
    _resultAddress = newResultAddress;

    notifyListeners();
  }
}

如你所见,将_resultAddress更改为notifyListeners()会告诉你,你可以显示它。你可以在代码中将_resultAddress更改为Consumer,如下所示:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MyWidgetTest extends StatelessWidget {
  const MyWidgetTest({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child:  Consumer<AddressProvider>(
        builder: (context, addressProvider ,snapshot) {
          return Row(
            children: [
              Expanded(
                child: Container(
                  height: 40,
                  color: primaryColor20,
                  child: Text(addressProvider.resultAddress ?? ''),
                ),
              ),
              ElevatedButton(
                onPressed: () async {
                  await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => KpostalView(
                        callback: (Kpostal result){
                          print(result.address);
                          /// here is you code to change
                          addressProvider.setResultAddress(result.address!);
                        },
                      ),
                    ),
                  );
                },
                child: Text('Find Address'),
              ),
            ],
          );
        }
      ),
    );
  }
}

请小心地将Provider包导入到pubspec.yaml中,并在main中提供Provider类,如下所示:

return runApp(MultiProvider(providers: [
    ListenableProvider.value(value: AddressProvider()),
  ], child: const MyApp()));

提供者作为状态管理的最大好处是你可以在任何你想用的地方使用你的变量。2快乐的编码...

相关问题