未来的建设者将制定白银清单

时间:2018-07-12 06:05:35

标签: dart flutter

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

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(),
    );

1 个答案:

答案 0 :(得分:2)

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