简体   繁体   English

如何在一个扑动的应用程序中解决json对象重复的问题?

[英]How to solve the problem of json objects duplication in a flutter app?

I'm trying to fetch json data from a php file hosted on a server and the link of the file is below: 我正在尝试从托管在服务器上的php文件中获取json数据,该文件的链接如下:

http://www.alkadhum-col.edu.iq/Teachers%20Activities/get.php http://www.alkadhum-col.edu.iq/Teachers%20Activities/get.php

I have a problem when i need to display my json data on my app screen it seems that there is one extra object added maybe to the json objects on the server or it might be through the flutter itself. 我有一个问题,当我需要在我的应用程序屏幕上显示我的json数据时,似乎有一个额外的对象可能添加到服务器上的json对象,或者它可能是通过flutter本身。 The image is shown below: 图像如下所示:

在此输入图像描述


在此输入图像描述

How can i solve this problem? 我怎么解决这个问题? and why my font size didn't changed?. 为什么我的字体大小没有改变?

The complete code is below: 完整代码如下:

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

void main() {
runApp(Workshops());
}

class Workshops extends StatelessWidget {
  @override
  Widget build(BuildContext mycontext) {
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO( 52, 73, 94, 1.0),
        automaticallyImplyLeading: false, // Don't show the leading button
        title: new Text("PHP with Flutter"),
        ),

        body: PostScreen(),
        )
    );
  }
}    

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {
  List<Post> _postList = [];

  Future<List<Post>> fetchPost() async {
    final response =
        await http.get('http://www.alkadhum-col.edu.iq/Teachers%20Activities/get.php');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values = new List<dynamic>();
      values = json.decode(response.body);
      print(values);
      if (values.length > 0) {
        for (int i = 0; i < values.length; i++) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            _postList.add(Post.fromJson(map));
          }
        }
      }

      return _postList;
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Post>>(
      future: fetchPost(),
      builder: (_, AsyncSnapshot<List<Post>> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        }

        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (_, index) {
            dynamic post = snapshot.data[index];
            return Card(
                child: new ListTile(
                  title: new Text(post.name, style: TextStyle(fontSize: 16.0),),
                  subtitle: new Text(post.msg, style: TextStyle(fontSize: 16.0),),
                  trailing: new Text(post.date, style: TextStyle(fontSize: 16.0),),
                ),
            );
          },
        );
      },
    );
  }

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

class Post {
  String name;
  String msg;
  String day;
  String date;

  Post({this.name, this.msg, this.day, this.date});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      name: json['name'],
      msg: json['msg'],
      day: json['day'],
      date:json['date']
    );
  }
}

you can see duplicates because Flutter calls build method multiple times ( https://api.flutter.dev/flutter/widgets/State/build.html ) 您可以看到重复项,因为Flutter多次调用build方法( https://api.flutter.dev/flutter/widgets/State/build.html

You can change your code to execute fetchPost on _PostScreenState creation only or just remove all elements before adding new ones. 您可以更改代码以fetchPost_PostScreenState创建时执行fetchPost ,或者在添加新元素之前删除所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM