Home > other >  How can I put a variable into Text in Flutter?
How can I put a variable into Text in Flutter?

Time:12-13

Newbie's Simple question. I would like to save the result of a variable created with a callback as a var and output it within the text of another widget. What should I do..?

                    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'),
                          ),
                        ],
                      ),

enter image description here

CodePudding user response:

use a StatefulWidget, then setState(() => resultAddress = result.address; such tax you can use Text(resultAddress)

CodePudding user response:

You have to use a 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'),
        ),
      ],
    );
  }
}

CodePudding user response:

You can use Text('My text ${result.address}') but to refresh the value you'll need it to be inside of a StatefulWidget

CodePudding user response:

you have 2 choices.

  1. use a StatefullWidget by using setState(() => resultAddress = result.address; this makes resultAddress changeable by using setState.
  2. using state management like Provider. create a class like this:
import 'package:flutter/material.dart';

class AddressProvider extends ChangeNotifier {
  String? _resultAddress;

  String? get resultAddress => _resultAddress;

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

    notifyListeners();
  }
}

as you see changing _resultAddress by notifyListeners() tells you and you can show it. you can use _resultAddress by Consumer like this in your codes:

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'),
              ),
            ],
          );
        }
      ),
    );
  }
}


be careful to import Provider package to your pubspec.yaml and provide your provider class in your main like this:

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

the best benefit of provider as state management is that you can use your variables where ever you want. Happy Coding...

  • Related