Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 使用分页颤振追加数据列表视图_Flutter_Dart_Flutter Layout - Fatal编程技术网

Flutter 使用分页颤振追加数据列表视图

Flutter 使用分页颤振追加数据列表视图,flutter,dart,flutter-layout,Flutter,Dart,Flutter Layout,单击按钮“获取更多数据”时如何添加数据lisview?我的当前代码仅使用新数据刷新。谢谢。 我的: 您可以添加完整照片以保留所有照片 在原始API代码中,在每页返回重复数据 因为在这个API的定义中,开始是数字而不是页面 因此,您需要更改该部分以满足您的要求 代码片段 Future<List<Photo>> fetchPhotos(http.Client client, int page) async { print('page la' + page.toString

单击按钮“获取更多数据”时如何添加数据lisview?我的当前代码仅使用新数据刷新。谢谢。 我的:


您可以添加完整照片以保留所有照片
在原始API代码中,在每页返回重复数据
因为在这个API的定义中,开始是数字而不是页面
因此,您需要更改该部分以满足您的要求

代码片段

Future<List<Photo>> fetchPhotos(http.Client client, int page) async {
  print('page la' + page.toString());
  final response = await client.get(
      'https://jsonplaceholder.typicode.com/photos?_start=' +
          page.toString() +
          '&_limit=2');

  var val = await compute(parsePhotos, response.body);
  print('val.lenght ${val.length}');
  fullPhotos.addAll(val);
  print('fullPhotos  ${fullPhotos.length}');
  return fullPhotos;
}

List<Photo> fullPhotos = [];
Future fetchPhotos(http.Client,int-page)异步{
打印('page la'+page.toString());
最终响应=等待client.get(
'https://jsonplaceholder.typicode.com/photos?_start=' +
page.toString()+
"和(u limit=2)",;
var val=等待计算(parsePhotos,response.body);
打印('val.lenght${val.length}');
完整照片。addAll(val);
打印('fullPhotos${fullPhotos.length}');
返回完整照片;
}
列出完整照片=[];
工作演示

完整代码

import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<List<Photo>> fetchPhotos(http.Client client, int page) async {
  print('page la' + page.toString());
  final response = await client.get(
      'https://jsonplaceholder.typicode.com/photos?_start=' +
          page.toString() +
          '&_limit=2');

  var val = await compute(parsePhotos, response.body);
  print('val.lenght ${val.length}');
  fullPhotos.addAll(val);
  print('fullPhotos  ${fullPhotos.length}');
  return fullPhotos;
}

List<Photo> fullPhotos = [];
// A function that will convert a response body into a List<Photo>
List<Photo> parsePhotos(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}

class Photo {
  final int albumId;
  final int id;
  final String title;
  final String url;
  final String thumbnailUrl;

  Photo({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  factory Photo.fromJson(Map json) {
    return Photo(
      albumId: json['albumId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      url: json['url'] as String,
      thumbnailUrl: json['thumbnailUrl'] as String,
    );
  }
}

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => new _State();
}

class _State extends State<MyApp> {
  //final String title;
  // MyHomePage({Key key, this.title}) : super(key: key);
  int page = 0;
  void _onPressed() {
    setState(() {
      page = page + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo get data'),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            RaisedButton(
                onPressed: _onPressed, child: new Text('Get more data')),
            Expanded(
              child: Padding(
                child: FutureBuilder<List<Photo>>(
                  future: fetchPhotos(http.Client(), page),
                  builder: (context, snapshot) {
                    if (snapshot.hasError) print(snapshot.error);
                    return snapshot.hasData
                        ? PhotosList(photos: snapshot.data)
                        : Center(child: CircularProgressIndicator());
                  },
                ),
                padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Photo> photos;

  PhotosList({Key key, this.photos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: photos.length,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[
            Container(
                margin: EdgeInsets.all(10),
                color: Colors.white10,
                alignment: Alignment.center,
                child: Card(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      ListTile(
                        leading: Image.network(
                          photos[index].thumbnailUrl,
                          fit: BoxFit.fitWidth,
                        ),
                        title: Text(photos[index].title),
                        subtitle: Text(photos[index].title),
                      ),
                      ButtonTheme.bar(
                        // make buttons use the appropriate styles for cards
                        child: ButtonBar(
                          children: <Widget>[
                            FlatButton(
                              child: const Text('Open'),
                              onPressed: () {/* ... */},
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                )),
          ],
        );
      },
    );
  }
}
导入'dart:async';
导入“dart:convert”;
进口“包装:颤振/基础.dart”;
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
未来的抓取照片(http.Client,int-page)异步{
打印('page la'+page.toString());
最终响应=等待client.get(
'https://jsonplaceholder.typicode.com/photos?_start=' +
page.toString()+
"和(u limit=2)",;
var val=等待计算(parsePhotos,response.body);
打印('val.lenght${val.length}');
完整照片。addAll(val);
打印('fullPhotos${fullPhotos.length}');
返回完整照片;
}
列出完整照片=[];
//将响应主体转换为列表的函数
列表照片(字符串响应库){
final parsed=json.decode(responseBody.cast();
返回parsed.map((json)=>Photo.fromJson(json)).toList();
}
班级照片{
最终的int-albumId;
最终int id;
最后的字符串标题;
最终字符串url;
最终字符串缩略图URL;
照片({this.albumId,this.id,this.title,this.url,this.thumbnailUrl});
factory Photo.fromJson(映射json){
返回照片(
albumId:json['albumId']作为int,
id:json['id']作为int,
title:json['title']作为字符串,
url:json['url']作为字符串,
thumbnailUrl:json['thumbnailUrl']作为字符串,
);
}
}
void main(){
runApp(新材料)PP(
主页:新建MyApp(),
));
}
类MyApp扩展了StatefulWidget{
@凌驾
_State createState()=>new_State();
}
类_状态扩展状态{
//最后的字符串标题;
//MyHomePage({Key,this.title}):超级(Key:Key);
int page=0;
void _onPressed(){
设置状态(){
页码=页码+1;
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“演示获取数据”),
),
主体:容器(
子:列(
儿童:[
升起的按钮(
onPressed:_onPressed,child:新文本(“获取更多数据”),
扩大(
孩子:填充(
孩子:未来建设者(
未来:获取照片(http.Client(),第页),
生成器:(上下文,快照){
if(snapshot.hasError)打印(snapshot.error);
返回snapshot.hasData
?照片列表(照片:快照。数据)
:居中(子项:循环压缩机指示器());
},
),
填充:来自LTRB(1.0,10.0,1.0,10.0)的边缘设置,
),
)
],
),
),
);
}
}
类PhotosList扩展了无状态小部件{
最后名单照片;
PhotosList({Key,this.photos}):super(Key:Key);
@凌驾
小部件构建(构建上下文){
返回ListView.builder(
itemCount:photos.length,
itemBuilder:(上下文,索引){
返回列(
儿童:[
容器(
保证金:所有(10),
颜色:颜色。白色,
对齐:对齐.center,
孩子:卡片(
子:列(
mainAxisSize:mainAxisSize.min,
儿童:[
列表砖(
领先:Image.net(
照片[索引]。缩略图URL,
适合:BoxFit.fitWidth,
),
标题:文本(照片[索引].标题),
字幕:文字(照片[索引].标题),
),
钮扣柄(
//使按钮使用适合卡片的样式
孩子:巴顿巴(
儿童:[
扁平按钮(
子项:常量文本(“打开”),
按下:(){/*…*/},
),
],
),
),
],
),
)),
],
);
},
);
}
}

感谢您的帮助,但您是否有解决方案将数据附加到列表视图而不使用_endparam?我已更新代码。您需要更改api调用。原始代码在每一页返回重复的数据