when I use a future builder to get data on the first tab of the bottom navigation bar from the backend it disappears when I change to the second tab bottom navigation bar.
why does it happen?
how do I fix this?
above is the page when I load the app for the first time and API gets hit.
above is the page when I change the bottom tab once and go back to the third tab again...
this happens every time...
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
class newExample extends StatefulWidget {
@override
newExampleState createState() => newExampleState();
}
class newExampleState extends State<newExample> {
var userid;
Future<http.Request> getData() async
{
var client = new http.Client();
final response = await client.get('http://182.0.0.102:5000/user_detail');
final responseJson = json.decode(response.body);
dynamic user_id = responseJson['user_id'];
userid = user_id;
print(responseJson);
client.close();
// return responseJson;
}
@override
void initState() {
super.initState();
getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: ListView.builder(
itemCount: userid.length,
itemBuilder: (BuildContext context, int index){
return _buildCards(context, index);
},
),
),
);
}
Widget _buildCards(BuildContext context, int index){
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child:
// Text('hi'),
Text('${userid[index]}'),
)
);
}
}
I think it's happening because you call
getData()
ininitState
and it will work only once. Try calling your function like this:Read about SchedulerBinding: https://api.flutter.dev/flutter/scheduler/SchedulerBinding/addPostFrameCallback.html