Flutter应用程序使用分页包和JSON

时间:2018-10-08 07:19:01

标签: json flutter

我正在使用分页程序包构建一个APP,并希望从外部JSON请求中获取totalCount var。

我有一个返回INT值的函数,该值将是totalCount,但是将其添加到totalCount参数时会返回错误:

type 'Future<int>' is not a subtype of type 'int'

我该如何解决?

更新:

return PagewiseGridView(
  pageSize: 6,
  totalCount: getTotals(),
  crossAxisCount: 2,
  mainAxisSpacing: 8.0,
  crossAxisSpacing: 8.0,
  childAspectRatio: 0.555,
  padding: EdgeInsets.all(15.0),
  itemBuilder: this._itemBuilder,
  pageFuture: BackendService.getPage,
);

这是创建网格的类。

3 个答案:

答案 0 :(得分:0)

From the dart documentation:

Future是Future对象,它代表产生类型T的结果的异步操作。

在您的情况下,您需要异步获取信息。

    // Performing a request

// ... some widget 
// ... child/Center is here just to exemplify how to use this Future inside a widget
// child: Center(child:  
    FutureBuilder<CustomList>(
        future: fetchPost(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // USE HERE THE DATA: 
            // snapshot.data.allCustoms        
            // snapshot.data.allCustoms.length 
            // for example you can create a ListView here  
    enter code here
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          return CircularProgressIndicator();
        })

    // Making a request example (called above) 

    Future<CustomList> fetchPost() async {
      final response = await http
          .get('https://some_api_example');

      if (response.statusCode == 200) {
        // was successful, parse 
        return CustomList.fromJson(json.decode(response.body));
      } else {
        // not successful, throw.
        throw Exception('Failed to load post');
      }
    }

    // Some custom object we need to parse 

    class Custom {
      final String id;
      final String info;

      Custom({this.id, this.info});

      factory Custom.fromJson(Map<String, dynamic> json) {
        return Custom(
          id: json['id'].replaceAll(" ", ""),
          info: json['info'].replaceAll(" ", "")
        );
      }
    }

    // A list of custom objects we parse from the reqeust

    class CustomList {
      final List<Custom> allCustoms;

      CustomsList({
        this.allCustoms,
      });

      factory CustomList.fromJson(List<dynamic> parsedJson) {
        allCustoms = new List<Custom>();
        allCustoms = parsedJson.map((i) => Custom.fromJson(i)).toList();

        return new CustomList(
          allCustoms: allCustoms,
        );
      }
    }

答案 1 :(得分:0)

请您尝试以下代码,让我知道您遇到什么错误。

return FutureBuilder<CustomList>(
    future: fetchPost(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {

        return PagewiseGridView(
          pageSize: 6,
          totalCount: snapshot.data,
          crossAxisCount: 2,
          mainAxisSpacing: 8.0,
          crossAxisSpacing: 8.0,
          childAspectRatio: 0.555,
          padding: EdgeInsets.all(15.0),
          itemBuilder: this._itemBuilder,
          pageFuture: BackendService.getPage,
        );

      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }
      return CircularProgressIndicator();
    })

答案 2 :(得分:0)

问题在于您无法将Future传递给期望为int的变量。

您需要等待将来的完成,而在等待期间,例如,可以显示居中的圆形指示器。

这是您可以在State类中使用的东西:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  State createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _totalCounter = -1;

  @override
  void initState() {
    super.initState();
    getTotalCounter();
  }

  void getTotalCounter() async {
    _totalCounter = await getTotals();
    setState(() {});
  }

  // Simulate your future
  Future<int> getTotals() {
    return Future.delayed(Duration(seconds: 3), () => 100);
  }

  @override
  Widget build(BuildContext context) {
    return _totalCounter == -1
        ? Center(child: CircularProgressIndicator())
        : PagewiseGridView(
            pageSize: 6,
            totalCount: _totalCounter,
            crossAxisCount: 2,
            mainAxisSpacing: 8.0,
            crossAxisSpacing: 8.0,
            childAspectRatio: 0.555,
            padding: EdgeInsets.all(15.0),
            itemBuilder: this._itemBuilder,
            pageFuture: BackendService.getPage,
          );
  }
}