REST API in flutter

6,069

Solution 1

Yes, you can easily use REST API's with Flutter.
Dart offers an http package for easy HTTP request and there are others available on Dart Pub.

With the http package, you can even integrate your REST API request into the build tree very easily using a FutureBuilder:

FutureBuilder(
  future: http.get('https://your-rest-api-domain.xyz/get-images?amount=5'),
  builder: (context, snapshot) {
    // you can easily work with your request results in here and return a widget
  },
)

As cricket_007 mentioned in a comment, Flutter also provides a cookbook entry on this topic.

Solution 2

Simple cade for calling REST API and display in a listview.

Step 1: Create a model class like this

class ItemSubCat{
  final String ItemCode;
  final String ItemName;

  ItemSubCat(
      {this.ItemCode, this.ItemName});

  factory ItemSubCat.fromJson(Map<String, dynamic> parsedJson){
    return ItemSubCat(
        ItemCode: parsedJson['ItemCode'],
        ItemName: parsedJson['ItemName']);
  }
}

Step 2:

List<ItemSubCat> parsePosts(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map<ItemSubCat>((json) => ItemSubCat.fromJson(json)).toList();
}

Future<List<ItemSubCat>> fetchsubcat(http.Client client) async {
  var connectivityResult = await (Connectivity().checkConnectivity());
  if (connectivityResult == ConnectivityResult.mobile||connectivityResult == ConnectivityResult.wifi) {

    final response = await client.get('Your Api Url');
    //print(response.body);
    return compute(parsePosts, response.body);
  } else  {
    Toast.show(message: "Please check your network conenction", duration: Delay.SHORT, textColor: Colors.black);
  }

}

Step 3:

class ItemSubCategory extends StatelessWidget {
  final String ItemCatCode;
  ItemSubCategory({Key key, @required this.ItemCatCode}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return  new Scaffold(
        appBar: AppBar(
          elevation: 0.0,
          backgroundColor: Colors.transparent,
          iconTheme: IconThemeData.fallback(),
          title: Text('Category', style: TextStyle(color: Colors.black)),
          centerTitle: true,
        ),
        body: FutureBuilder<List<ItemSubCat>>(
          future: fetchsubcat(http.Client()),
          builder: (context, snapshot) {
            if (snapshot.hasError) print(snapshot.error);
            return snapshot.hasData
                ? GridViewPosts(items: snapshot.data)
                : Center(child: CircularProgressIndicator());
          },
        ),
      );

  }
}

Step 4:

class GridViewPosts extends StatelessWidget {
  final List<ItemSubCat> items;
  GridViewPosts({Key key, this.items}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
        child: new GridView.builder(
            itemCount: items.length,
            shrinkWrap: true,
            gridDelegate:
            new SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3),
            itemBuilder: (BuildContext context, int position) {
              return new  Column(
                children: <Widget>[
                  Divider(height: 0.0),
                  cardDetails(--You pass your data to listitems--),
                ],


              );

            })
    );
  }


}

Here you design your widget for a list item (cardDetails)

Share:
6,069
Coder
Author by

Coder

I am a person who enjoys doing app development and who also enjoys doing projects with complicated algorithms.

Updated on December 06, 2022

Comments

  • Coder
    Coder over 1 year

    I have a project in which I have a Python database and I have a Flutter ui.
    Is there anyway I can use the REST API to connect them? My teammates who do the backend state that their database will use the REST API, so it would be useful if I can do that.