【问题标题】:my snapshot doesn't have the data in futurebuilder我的快照没有 futurebuilder 中的数据
【发布时间】:2020-12-27 07:33:44
【问题描述】:

请帮忙,如果可以的话。我正在尝试从 rest api 获取一些数据。但是在 getTreadingWallpapers() 方法上,它向我显示了完整的 json 数据。但是每当我在其他条件下打印 snapshot.hasError 时......它显示我是错误的。这意味着快照没有错误..但是为什么我没有在我未来的构建器中获取数据。没有显示错误,我该如何解决这个问题

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


          },
        )


    );
  }
}

【问题讨论】:

    标签: flutter dart flutter-layout rest


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    第一步:不需要isLoading,可以直接使用check ConnectionState
    第2步:你不需要声明List&lt;RecentPage&gt; wallpaperssnapshot.data已经保留这个

    代码sn-p

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 看,我已经编辑了结果..即使我返回了一些东西..它显示我是错误的..然后给出一些错误
      • 您返回的wallpapers 变量是否有数据?
      • 否,先返回false,返回错误后很快
      • 我的意思是从您的 getTrendingWallpapers 方法返回数据我复制了您的代码并稍微简化了一下,Future 会显示数据。
      • 顺便说一句,你没有以正确的方式使用FutureBuilder
      猜你喜欢
      • 2021-11-17
      • 2020-05-01
      • 2020-09-10
      • 2021-12-26
      • 2020-04-12
      • 2020-07-20
      • 2021-04-13
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多