[英]I am trying to fetch collection from shopify admin api with rest api in flutter
I am Using flutter with http package.我正在使用 flutter 和 http package。 in my code
CircularProgressIndicator()
is running and is not showing any error here is my http request code在我的代码中
CircularProgressIndicator()
正在运行并且没有显示任何错误这里是我的 http 请求代码
import 'package:http/http.dart' as http;
import 'dart:convert';`
class Collections {
Future<List> getAllCollections() async {
var headers = {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': '{token}',
};
var url = Uri.parse(
'https://{shop}.myshopify.com/admin/api/2022-07/collections.json');
try {
var res = await http.get(url, headers: headers);
print(res);
if (res.statusCode == 200) {
return jsonDecode(res.body);
} else {
return Future.error("Server Error");
}
} catch (SocketException) {
return Future.error("Error Fetching Data");
}
}
}
and here I created the object of this class and using it.在这里我创建了这个 class 的 object 并使用它。
class ProCategories extends StatefulWidget {
const ProCategories({Key? key}) : super(key: key);
@override
State<ProCategories> createState() => _ProCategoriesState();
}
class _ProCategoriesState extends State<ProCategories> {
Collections collections = Collections();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Categories"),
centerTitle: true,
foregroundColor: Colors.black,
backgroundColor: Colors.white,
),
body: Container(
margin: EdgeInsets.only(top: 8.0),
child: FutureBuilder<List>(
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data?.length == 0) {
return Center(
child: Text("0 Collections"),
);
}
return ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Row(
children: [
Expanded(
child: Container(
child: Text(
snapshot.data![index]['collections']['edges']
['node']['title'],
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold),
),
),
),
],
),
),
);
});
} else if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
),
);
}
}
Add future to FutureBuilder
.将未来添加到
FutureBuilder
。
late Future<List> getAllCollections;
@override
void initState() {
super.initState();
getAllCollections = collections.getAllCollections();
}
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: Container(
margin: EdgeInsets.only(top: 8.0),
child: FutureBuilder<List>(
future: getAllCollections,
builder: (context, snapshot) {
...
},
),
),
);
}
See Fetch data from the internet for the full example.有关完整示例,请参阅从 Internet 获取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.