如何解决Flutter应用中json对象重复的问题?

时间:2019-06-22 21:09:46

标签: json http flutter dart

我正在尝试从服务器上托管的php文件中获取json数据,并且该文件的链接如下:

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

当我需要在我的应用程序屏幕上显示我的json数据时,我遇到一个问题,似乎有一个额外的对象可能添加到了服务器上的json对象中,或者可能是通过flutter本身。该图像如下所示:

enter image description here


enter image description here

我该如何解决这个问题?为什么我的字体大小没有变化?

完整的代码如下:

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

1 个答案:

答案 0 :(得分:0)

您会看到重复的内容,因为Flutter多次调用build方法(https://api.flutter.dev/flutter/widgets/State/build.html

您可以将代码更改为仅在创建fetchPost时执行_PostScreenState,或在添加新元素之前删除所有元素。