0
votes

I have a StreamBuilder inside my Widget build:

StreamBuilder(
  stream: stream.asStream(),
  builder: (BuildContext context, AsyncSnapshot snapshot) {
...

The stream is defined inside the void initState. The fetchPost() calls information from an Api:

@override
  void initState() {
    super.initState();

    setState(() {
      stream = fetchPost();
    });

  }

The fetchPost():

Future<List<User>> fetchPost() async {
  final response = await http.get('url');
  final jsonResponse = json.decode(response.body);

  List<User> users = [];

  for(var u in jsonResponse){
    User user = User(
      id: u["id"].toString(), 
      uname: u["username"],
      firstname: u["firstname"],
      lastname: u["lastname"],
      email: u["email"],
    );
    users.add(user);
  }
  return users;
}

After I change something in the list (also the api changes) via a new Page it Navigates back to the StreamBuilder:

Navigator.pushReplacement(
  context,
  new MaterialPageRoute(builder: (context) => new UserDart())
);        

But the StreamBuilder sometimes do not refresh. What do I need to do that it refreshes the data. So it needs to call the fetchPost() everytime the Page gets loaded but how?

1
What is the return type of fetchPost()? - lordvidex
it returns a list of users. - Timebreaker900
@lordvidex I added it to the question. - Timebreaker900
do setState() inside initState method is not clever idea - user10539074
@Eugene I could also write it inside the StreamBuilder with stream: fetchPost().asStream(), but it still refreshes 8 out of 10 time. I don't understand why it somtime do refresh and sometimes not.. - Timebreaker900

1 Answers

1
votes

You could write like this

    Navigator.pushReplacement(context,new MaterialPageRoute(
        builder: (context) => new UserDart())).then((onValue) {
                 fetchPost();  // this will called when it navigates back from UserDart 
    });