skip to Main Content

In my code when open this page then call fetchData() method in initState.fetchData methos call every 15 seconds.
initState

Timer? timer;
  Future<List<DataDoctor>>? future;
  @override
  void initState() {
    super.initState();

    timer = Timer.periodic(Duration(seconds: 15), (Timer t) => fetchData());
  }

in fetchData method geting data from API call in the API has
these data.

[![enter image description here][2]][2] those data should retrieve to backend for now I only retrieve only Boolean value.
like as my code this Boolean value I get as doctor_in variable. if doctor_in false then should recall again API and should get data. it should at every 15 seconds until open this page.

data retrieve code

  FutureBuilder<DataDoctor> fetchData() {
    builder:
    (context, snapshot) {
      if (snapshot.hasData) {
        if (snapshot.data!.doctor_in == false) {
          future = client.isDoctorActive();
        }
      } else if (snapshot.hasError) {
        return Text('${snapshot.error}');
      }
    };
  }

model

class DataDoctor {
  String channelName;
  String receiver_name;
  bool doctor_in;

  DataDoctor(
      {required this.channelName,
      required this.receiver_name,
      required this.doctor_in});

  factory DataDoctor.fromJson(Map<String, dynamic> json) {
    return DataDoctor(
      channelName: json['Mobile'] == null ? null : json['Mobile'],
      receiver_name: json['Name'] == null ? null : json['Name'],
      doctor_in: json['Boolean'] == null ? null : json['Boolean'],
    );
  }
}

api call

class ApiServiceDataDoctor {
  final String url =
      'https://tools.learningcontainer.com/sample-json-file.json';
  Future<List<DataDoctor>> isDoctorActive() async {
    Response response = await get(Uri.parse(url));
    if (response.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(response.body);

      Map<String, dynamic> body = json['dataActive'];
      List<DataDoctor> datas = [DataDoctor.fromJson(body)];
      return datas;
    } else {
      throw ('cannot fetch data');
    }
  }
}

if doctor_in == true then ElevatedButton should enable

2

Answers


  1. Simply make the future nullable or provide some default value. It is throwing exception because the value can be null which will crash the application.

    Login or Signup to reply.
  2. FutureBuilder<DataDoctor> fetchData() {
        builder:
        (context, snapshot) {
          if (snapshot.hasData) {     // ⚠ This if statement is not returning anything, So you are getting error
            if (snapshot.data!.doctor_in == false) {
              future = client.isDoctorActive();
              return Text(`${snapshot.data}`);
            }
           if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }
           return Text(`${snapshot.error}`) // 👈 Add this return statement 
        };
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search