【问题标题】:Returning null values with all types of returning data Flutter使用所有类型的返回数据返回 null 值 Flutter
【发布时间】:2021-07-02 22:44:31
【问题描述】:

我正在尝试StreamBuilder,所以我调用了 API,快照的返回值始终为空。当我打印print(snapshot.error.toString()); 时,它返回null。我试过以不同的方式解析数据,但没有这样做。完整代码如下:

  var posts = <Post>[];
  var controller = StreamController<List<Post>>();

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

  fetchPosts() async {
    final resp =
        await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
    final data = json.decode(resp.body);

    posts = data.map<Post>((e) => Post()).toList();
    print(posts.isEmpty); // returns false
    pirnt(data); // returns the entire data
    controller.add(posts);
  }

  bool isSwitched = false;
  void toggleSwitch(bool value) {
    if (isSwitched == false) {
      controller.add(posts..sort((k1, k2) => k1.id.compareTo(k2.id)));
      print('Switch Button is ON');
    } else {
      controller.add(posts..sort((k1, k2) => k2.id.compareTo(k1.id)));

      print('Switch Button is OFF');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: TextButton(
                  child: Text('sort ascending'),
                  onPressed: () {
                    toggleSwitch(isSwitched = !isSwitched);
                  }),
            ),
          ],
        ),
        Expanded(
          child: StreamBuilder<List<Post>>(
            initialData: posts,
            stream: controller.stream,
            builder: (ctx, snapshot) {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  print(snapshot.error.toString);
                  Post post = snapshot.data[index];
                  return ListTile(
                    title: Text('${posts[index].id}'), // returns null
                    subtitle: Text('${post.id}'), // returns null
                    trailing: Text('${snapshot.data[index].id}'), // returns null
                  );
                },
              );
            },
          ),
        ),
      ],
    );
  }

后模型:

import 'package:flutter/foundation.dart';
import 'dart:core';

class Post extends ChangeNotifier {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

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

我是否在 API 调用中解析了错误的数据?或者是别的什么?提前感谢您的帮助。

【问题讨论】:

  • print(snapshot.error.toString); -> print(snapshot.error);(或print(snapshot.error.toString());
  • 它返回null。我没有意识到我错过了打印语句中的括号,我将编辑问题。
  • 所以如果snapshot.error为空也没关系,你需要改变:(e) =&gt; Post() -> (e) =&gt; Post.fromJson(e)
  • 我总是忘记在dart中解析JSON对象是不同的,它不像JS。再次感谢伙计,这些天你是我的救星/朋友。 :)

标签: json flutter mobile flutter-dependencies


【解决方案1】:

所以我的新老师/朋友@pskink 这些天让我学习并使用我的大脑,再次帮助我认识到错误。始终确保按应有的方式解析 JSON 数据。就我而言,我忘记了fetchPosts() 方法中的fromJson(e)。 所以这个问题的答案是:

posts = data.map<Post>((e) => Post.fromJson(e)).toList();

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 2021-05-02
    • 2021-06-07
    • 2023-01-16
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2019-08-05
    相关资源
    最近更新 更多