pls,请帮忙。我正尝试从rest api中获取一些数据。但是在getTreadingWallpapers()方法上,它显示了完整的json数据。但是每当我在其他条件下打印snapshot.hasError时,它就会显示为false。这意味着快照没有错误..但是为什么我将来的构建器中没有得到数据。没有错误显示,我该如何解决这个问题
class _FrontPageState extends State<FrontPage> {
Future<List<RecentPage>> recentPage;
RecentPage recentPagee;
bool isLoading = true;
List<RecentPage> wallpapers = new List();
Future<List<RecentPage>> getTrendingWallpapers() async {
// final url ="http://wallpaper.pkappstudio.info/api/api.php?action=get_recent";
String url = 'http://wallpaper.pkappstudio.info/api/api.php?action=get_recent';
final response =
await Http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final Map = jsonDecode(response.body);
print("${response.body}");
isLoading = false;
final recentPaget = recentPageFromJson(response.body).asMap();
recentPaget.entries.forEach((element) => wallpapers.add(element.value));
return wallpapers;
} else {
throw Exception('Failed to load post');
}
}
@override
void initState() {
// TODO: implement initState
recentPage = getTrendingWallpapers();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: brandName(),elevation: 0.0,),
body: FutureBuilder(
future: recentPage,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none &&
snapshot.hasData == null) {
print('project snapshot data is: ${snapshot.data}');
return isLoading? Center(child: Container(child: Text("container"),)):Center(child: Container(child: Text("csdsdontainer"),));
}
if(snapshot.hasData){
return isLoading? Center(child: CircularProgressIndicator()):ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index){
return Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
physics: ClampingScrollPhysics(),
childAspectRatio: 0.6,
mainAxisSpacing: 6.0,
crossAxisSpacing: 6.0,
children: wallpapers.map((wallpapers){
return GridTile(child: GestureDetector(
onTap: (){
// Navigator.push(context, MaterialPageRoute(builder: (context)=>ImageView(
// imageUrl: wallpapers.src.potrait,
// )));
},
child: Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child:Image.network(snapshot.data.imageUrl, fit: BoxFit.cover,),
),
),
));
}).toList(),
),
);
},
);
} else return Container(child: Text("${snapshot.hasError}"),);
},
)
);
}
}
答案 0 :(得分:1)
您可以在下面复制粘贴运行完整代码
步骤1:您不需要isLoading
,可以直接使用支票ConnectionState
步骤2:您不需要声明List<RecentPage> wallpapers
,snapshot.data
已经保留此
代码段
builder: (context, AsyncSnapshot<List<RecentPage>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
physics: ClampingScrollPhysics(),
childAspectRatio: 0.6,
mainAxisSpacing: 6.0,
crossAxisSpacing: 6.0,
children: snapshot.data.map((wallpapers) {
return GridTile(
child: GestureDetector(
onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context)=>ImageView(
// imageUrl: wallpapers.src.potrait,
// )));
},
child: Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
wallpapers.imageUrl,
fit: BoxFit.cover,
工作演示
完整代码
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
List<RecentPage> recentPageFromJson(String str) =>
List<RecentPage>.from(json.decode(str).map((x) => RecentPage.fromJson(x)));
String recentPageToJson(List<RecentPage> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class RecentPage {
RecentPage({
this.no,
this.imageId,
this.imageUpload,
this.imageUrl,
this.type,
this.viewCount,
this.downloadCount,
this.featured,
this.tags,
this.categoryId,
this.categoryName,
});
int no;
String imageId;
String imageUpload;
String imageUrl;
Type type;
String viewCount;
String downloadCount;
Featured featured;
String tags;
String categoryId;
String categoryName;
factory RecentPage.fromJson(Map<String, dynamic> json) => RecentPage(
no: json["no"],
imageId: json["image_id"],
imageUpload: json["image_upload"],
imageUrl: json["image_url"],
type: typeValues.map[json["type"]],
viewCount: json["view_count"],
downloadCount: json["download_count"],
featured: featuredValues.map[json["featured"]],
tags: json["tags"],
categoryId: json["category_id"],
categoryName: json["category_name"],
);
Map<String, dynamic> toJson() => {
"no": no,
"image_id": imageId,
"image_upload": imageUpload,
"image_url": imageUrl,
"type": typeValues.reverse[type],
"view_count": viewCount,
"download_count": downloadCount,
"featured": featuredValues.reverse[featured],
"tags": tags,
"category_id": categoryId,
"category_name": categoryName,
};
}
enum Featured { YES, NO }
final featuredValues = EnumValues({"no": Featured.NO, "yes": Featured.YES});
enum Type { UPLOAD }
final typeValues = EnumValues({"upload": Type.UPLOAD});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
class FrontPage extends StatefulWidget {
@override
_FrontPageState createState() => _FrontPageState();
}
class _FrontPageState extends State<FrontPage> {
Future<List<RecentPage>> recentPage;
RecentPage recentPagee;
bool isLoading = true;
List<RecentPage> wallpapers = new List();
Future<List<RecentPage>> getTrendingWallpapers() async {
// final url ="http://wallpaper.pkappstudio.info/api/api.php?action=get_recent";
String url =
'http://wallpaper.pkappstudio.info/api/api.php?action=get_recent';
final response =
await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final Map = jsonDecode(response.body);
print("${response.body}");
isLoading = false;
final recentPaget = recentPageFromJson(response.body).asMap();
recentPaget.entries.forEach((element) => wallpapers.add(element.value));
return wallpapers;
} else {
throw Exception('Failed to load post');
}
}
@override
void initState() {
// TODO: implement initState
recentPage = getTrendingWallpapers();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("brandName()"),
elevation: 0.0,
),
body: FutureBuilder(
future: recentPage,
builder: (context, AsyncSnapshot<List<RecentPage>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
physics: ClampingScrollPhysics(),
childAspectRatio: 0.6,
mainAxisSpacing: 6.0,
crossAxisSpacing: 6.0,
children: snapshot.data.map((wallpapers) {
return GridTile(
child: GestureDetector(
onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context)=>ImageView(
// imageUrl: wallpapers.src.potrait,
// )));
},
child: Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
wallpapers.imageUrl,
fit: BoxFit.cover,
),
),
),
));
}).toList(),
),
);
},
);
}
}
}));
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: FrontPage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
答案 1 :(得分:0)
FutureBuilder
小部件的实现很好
Future<List<dynamic>> getTrendingWallpapers() async {
String url = 'http://wallpaper.pkappstudio.info/api/api.php?action=get_recent';
final response = await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
List<dynamic> wallpapers = List();
wallpapers.add(response.body);
return wallpapers;
} else {
throw Exception('Failed to load post');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: getTrendingWallpapers(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting || snapshot.connectionState == ConnectionState.none) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(
child: Text('Future error'),
);
}
if (snapshot.hasData) {
return Center(
child: Text('Do something with your snapshot.data : \n ${snapshot.data}'),
);
}
},
),
);
}