REST API扑朔迷离

时间:2018-08-18 18:33:35

标签: database rest api flutter

我有一个项目,其中有一个Python数据库,并且有Flutter ui。
无论如何,我可以使用REST API来连接它们吗?我的后端团队成员说他们的数据库将使用REST API,因此如果可以的话将非常有用。

2 个答案:

答案 0 :(得分:7)

是的,您可以在Flutter中轻松使用REST API。
Dart offers an http package可以轻松进行HTTP请求,而Dart Pub上还有其他可用。

借助http软件包,您甚至可以使用FutureBuilder轻松地将REST API请求集成到构建树中:

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
  },
)

正如cricket_007在评论中提到的,Flutter也provides a cookbook entry on this topic

答案 1 :(得分:0)

用于调用REST API并显示在列表视图中的简单教程。

步骤1: 创建这样的模型类

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']);
  }
}

第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);
  }

}

第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());
          },
        ),
      );

  }
}

第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--),
                ],


              );

            })
    );
  }


}

您在这里为列表项(cardDetails)设计窗口小部件