0

This is my function:

getData() async {
final response = await Provider.of<PostApiService>(context, listen: false)
    .getData(1.toString() + '/service_contracts');
print(response.statusCode);
print(response.body);
var getData = GetModel.fromJson(response.body);
print(getData.company_name);
}

I want to use getData in my widget tree.

Radovan
  • 31
  • 4
  • 1
    Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt May 24 '21 at 13:54

1 Answers1

0

You'll need a StatefulWidget:

class YellowBird extends StatefulWidget {
  const YellowBird({ Key? key }) : super(key: key);

  @override
  _YellowBirdState createState() => _YellowBirdState();
}

class _YellowBirdState extends State<YellowBird> {
  // create variable to hold your data:
  dynamic data;
  // change dynamic to the type of the data you have
  // note: it will be null by default so might have to give
  // it an initial value.

Future<void> getData() async {
    final response = await Provider.of<PostApiService>(context, listen: 
    false).getData(1.toString() + '/service_contracts');
    final _getData = GetModel.fromJson(response.body);
    print(_getData.company_name);
    
    // now set the state
    // this will rebuild the ui with the latest
    // value of the data variable
    setState(() => data = _getData);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Column(
    children: <Widget>[
      Text('Data is: $data'),
      TextButton(
        child: Text('Get data'), 
        onPressed: getData,
      ),
    ], ), );
  }
}
Andrej
  • 2,743
  • 2
  • 11
  • 28