步骤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--),
],
);
})
);
}
}