gpt4 book ai didi

dart - Future Builder 制作 Sliver Lists

转载 作者:IT王子 更新时间:2023-10-29 06:41:32 25 4
gpt4 key购买 nike

我正在尝试从 GET 请求生成一个动态的 slivers 列表。但是我遇到了麻烦,似乎响应数据为空。这是我的代码:

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


class HomepageBody extends StatefulWidget{
@override
State<StatefulWidget> createState() {

return HomepageBodyState();
}
}

class HomepageBodyState extends State <HomepageBody> {


@override
Widget build(BuildContext context) {
return new Expanded(
child: new Container(
color: new Color(0xFF736AB7),
child: new FutureBuilder <List<Post>>(
future: fetchPost(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) print(snapshot.error);
else
return jobscroll(context, snapshot);
//: Center(child: CircularProgressIndicator());
}


),
),
);
}
}

Future<List<Post>>fetchPost() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts?userId=1');

return compute(parsePosts, response.body);

}


List<Post> parsePosts(String responseBody){
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

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

}


class Post {

final String userId;
final String hashtag;
final String price;
final String description;

Post({this.userId, this.hashtag, this.price, this.description});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
hashtag: json['id'],
price: json['title'],
description: json['body'],
);
}

}


Widget jobscroll(BuildContext context, AsyncSnapshot snapshot) {

List data = snapshot.data;

return CustomScrollView(
scrollDirection: Axis.vertical,
shrinkWrap: false,
slivers: <Widget>[new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
sliver: new SliverList(
delegate: new SliverChildBuilderDelegate(
(context, index) => new BoardSummary(data[index]),
childCount: data.length,
),
),
),
],
);
}

BoardSummary 是一个无状态的小部件类,它只是使用每个“帖子”上的属性创建一个“卡片”。它接收类型为“Post”的对象。

控制台吐出很多错误,但这是最后一个似乎有意义的错误,它也出现在我的模拟器中:

I/flutter (18882): Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null.

编辑这也是我松弛跟踪的前几行:

E/flutter (13964): type 'int' is not a subtype of type 'String'
E/flutter (13964): #0 new Post.fromJson (file:///home/daniel/Desktop/testapp/lib/ui/homePageBody.dart:76:19)
E/flutter (13964): #1 parsePosts.<anonymous closure> (file:///home/daniel/Desktop/testapp/lib/ui/homePageBody.dart:60:40)
E/flutter (13964): #2 MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
E/flutter (13964): #3 ListIterable.toList (dart:_internal/iterable.dart:219:19)
E/flutter (13964): #4 parsePosts (file:///home/daniel/Desktop/testapp/lib/ui/homePageBody.dart:60:56)
E/flutter (13964): #5 _IsolateConfiguration.apply (package:flutter/src/foundation/isolates.dart:88:16)
E/flutter (13964): #6 _spawn.<anonymous closure> (package:flutter/src/foundation/isolates.dart:96:30)

我该怎么办?

编辑 将这段代码转换为字符串使其工作,只是要修复溢出。如果有更好的解决方案,请随时分享!

  return Post(
userId: json['userId'].toString(),
hashtag: json['id'].toString(),
price: json['title'].toString(),
description: json['body'].toString(),
);

最佳答案

FutureBuilder 会立即构建,即使值尚不可用,因为 build() 是同步的,不能延迟。

FutureBuilder 示例展示了如何检查该值是否已经可用(default: ... 而不是 snapshot.hasError):

new FutureBuilder<String>(
future: _calculation, // a Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('Press button to start');
case ConnectionState.waiting: return new Text('Awaiting result...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Text('Result: ${snapshot.data}');
}
},
)

关于dart - Future Builder 制作 Sliver Lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51298336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com