Micheal Ross
Micheal Ross

Reputation: 211

FutureBuilder return passed to var Flutter

I need to store some data inside a ".txt" file into a variable. To do this I'm using a FutureBuilder. The idea is to handle the reading action (async) with FutureBuilder and pass the FutureBuilder return to my global variable that will be updated when needed.

  Future<String> _read() async {
   try {
   final file = await _localBio;
   String body = await file.readAsString();
   // Read the file.
   return body;
   } catch (e) {
   // If encountering an error, return 0.
   return "Can't read";
 }
}

var bio ="";

String _ReadBio(){
FutureBuilder<String>(
  future: _read(),
  builder: (context, snapshot){
    if (snapshot.hasData) {
      bio=snapshot.data.toString(); //this isn't done
      return Text("");
    }
    else {
      return Text("Error occured");
    }
  }
);
return "";
}

Then in the TextField I want to show what is stored inside bio that should be the content of "bio.txt".

child: Text(
 _ReadBio()== "" //always true if no error occured
 ? bio
 : "Tell us something about you...",
 ),

But what is showed is the first bio value, I don't know why.

Upvotes: 0

Views: 225

Answers (1)

Blasanka
Blasanka

Reputation: 22417

I strongly suggest you to read about FutureBuilder.

You are missing the point od FutureBuilder because its is a widget to place in a widget tree what you have done is placed on a function that returns a empty string.

Instead you can do it like this,

Future<Widget> _readAndBuildBioWidget(){
   return FutureBuilder<String>(
     future: _read(),
     builder: (context, snapshot){
       if (snapshot.hasData) {
         bio=snapshot.data.toString(); //this isn't done
         return Text(bio ?? "");
       }
       else {
         return Text("Error occured");
      }
    }
  );
  return "";
}

@override
void build() {
   return Scaffold(
     child: _readAndBuildBioWidget(),
   );
}

Or you can do as below,

class _HomeScreenState extends State<HomeScreen> {
  var bio = "";

  Future<String> _read() async {
    try {
      final file = await _localBio;
      String body = await file.readAsString();
      return body;
    } catch (e) {
      return "Can't read";
    }
  }

  @override
  void initState() {
    _read().then((onValue) => bio = onValue);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text(bio ?? "")),
    );
  }
}

Note above code snippet I haven't tested. I just wanted to give a rough idea.

Upvotes: 1

Related Questions