Home > Net >  How do I incorporate a function where return is a String into a string?
How do I incorporate a function where return is a String into a string?

Time:08-28

I created a function with a return value of String as follows.

 Future<String?> setName() {
    String? name='Jon';

    return name;
  }

Is there any way to incorporate this into the string? I want to use following situations.

print('Name:${setName}');

or

    appBar: AppBar(
      title: Text('Name:${setName}'),

When I wrote the above, it unexpectedly output the following

Name:Closure:()=> Future<String?> from Function ...

CodePudding user response:

You could either set a variable to the current state (loading, loaded) and switch the UI accordingly like

return isLoading ? LoadingView() : LoadedView()

or you just pass the future in a FutureBuilder and handle the logic inside it

return FutureBuilder<String>(
        future: setName(), // a previously-obtained Future<String> or null
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.hasData) {
           return LoadedView();
          } else {
           return LoadingView();
        },
        }
      ),
    );

CodePudding user response:

It would be better if you use FutureBuilder for future method.

Create a state future variable.

class _TestXState extends State<TestX> {
  Future<String?> setName() async {
    String? name = 'Jon';
    await Future.delayed(Duration(seconds: 2));
    return name;
  }

  late final nameFuture = setName();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: FutureBuilder(
          future: nameFuture,
          builder: (context, snapshot) {
            if (snapshot.hasData) return Text("${snapshot.data}");
            return Text("....");
          },
        ),
      ),
    );
  }
}
  • Related