Home > Enterprise >  how to pass variables future function to extend statefulwidget
how to pass variables future function to extend statefulwidget

Time:01-05

in my code in HomeeScreen class I call Future function , In that future function fecth data from API and display in console nicely. print(datas[0].field2Value); this is the code line.And aslo that is the boolean value I want to get that value to class _HomeeScreenState extends State and deaclare to a bool variable. like this bool field2Value = datas[0].field2; but then show this error.

code

class _HomeeScreenState extends State<HomeeScreen> {
  Timer? timer;
  Future<List<DataList>>? future;
  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(
        Duration(seconds: 15), (Timer t) => isDoctorActive(widget.id));
  }

  bool field2Value = datas[0].field2Value;

  final String url = 'https://exampleapi.com/api/calls/?check=';
  Future<List<DataList>> isDoctorActive(String id) async {
    Response response = await get(Uri.parse(url   id));
    if (response.statusCode == 200) {
      print("apicall : "   id);
      Map<String, dynamic> json = jsonDecode(response.body);

      Map<String, dynamic> body = json['data'];
      List<DataList> datas = [DataList.fromJson(body)];
      print(datas[0].field2Value);

      return datas;
    } else {
      throw ('cannot fetch data');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
            onPressed: field2Value ? joinVideoRoom : null, child: Text("Join")),
      ),
    );
  }

  Future<void> joinVideoRoom() async {
    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => NextScreen(),
        ));
  }
}

CodePudding user response:

Why don't you just accept another argument in your function? meaning:

isActive(String id, myArgument)
class _HomeeScreenState extends State<HomeeScreen> {
    
 
bool field2Value = datas[0].field2;
final String url = 'https://exampleapi.com/api/calls/?check=';

Future<List<DataList>> isActive(String id, field2) async {
  ....
  print(field2)
   
  }
  • Related