从dart中的JSON调用返回列表

时间:2019-03-31 18:03:45

标签: dart flutter

编辑:

整个DART文件-这是整个DART文件。我没有看到如何在ARR声明中调用该方法并返回正确的映射。只需从http调用生成数组,我们就很好了。这是我们的首次运行,它从JSON返回多个记录并进行遍历。

  import 'package:flutter/material.dart';
 import 'package:lightbridge_mobile/screens/forum/assets/colors.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:lightbridge_mobile/screens/forum/assets/app_bar_forum.dart';
import 'package:lightbridge_mobile/models/forum_answers.dart';
 import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

 class ForumDetailPage extends StatefulWidget {
 @override
 _ForumDetailPageState createState() => new _ForumDetailPageState();
}

 class _ForumDetailPageState extends State<ForumDetailPage> {
  @override
 Widget build(BuildContext context) {
var questionSection = new Padding(
  padding: const EdgeInsets.all(8.0),
  child: new Column(
    children: <Widget>[
      new Text(
        // Post Title
        "How do I become a expert in programming as well as design ??",
        textScaleFactor: 1.5,
        style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0 ),
      ),
      new Padding(
        padding: const EdgeInsets.all(10.0),
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            new IconWithText(Icons.laptop_windows, "Technology", iconColor: Colors.grey),
            new IconWithText(
              Icons.question_answer,
              "Answered",
              iconColor: Colors.grey,
            ),
            new IconWithText(Icons.remove_red_eye, "54", iconColor: Colors.grey)
          ],
        ),
      ),
      new Divider( height: 1.0)
    ],
  ),
);

var responses = new Container(
  padding: const EdgeInsets.all(8.0),

  child: new ListView.builder(
    itemBuilder: (BuildContext context, int index) => new ForumPost(ForumPostArr[index]),
    itemCount: ForumPostArr.length,
  )
);

return new Scaffold(
   appBar : LBForumAppBar().getAppBar(),
  body: new Column(
    children: <Widget>[
      questionSection,
      new Expanded(
          child: new Padding(
        padding: const EdgeInsets.only(bottom: 20.0),
        child: responses,
      ))
    ],
  ),
);
 }
}

var ForumPostArr =  [
 new ForumPostEntry("User1", "2 Days ago", 0 , 0 , "Hello,\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
 new ForumPostEntry("User2", "23 Hours ago", 1 , 0 , "Pellentesque justo metus, finibus porttitor consequat vitae, tincidunt vitae quam. Vestibulum molestie sem diam. Nullam pretium semper tempus. Maecenas lobortis lacus nunc, id lacinia nunc imperdiet tempor. Mauris mi ipsum, finibus consectetur eleifend a, maximus eget lorem. Praesent a magna nibh. In congue sapien sed velit mattis sodales. Nam tempus pulvinar metus, in gravida elit tincidunt in. Curabitur sed sapien commodo, fringilla tortor eu, accumsan est. Proin tincidunt convallis dolor, a faucibus sapien auctor sodales. Duis vitae dapibus metus. Nulla sit amet porta ipsum, posuere tempor tortor.\n\nCurabitur mauris dolor, cursus et mi id, mattis sagittis velit. Duis eleifend mi et ante aliquam elementum. Ut feugiat diam enim, at placerat elit semper vitae. Phasellus vulputate quis ex eu dictum. Cras sapien magna, faucibus at lacus vel, faucibus viverra lorem. Phasellus quis dui tristique, ultricies velit non, cursus lectus. Suspendisse neque nisl, vestibulum non dui in, vulputate placerat elit. Sed at convallis mauris, eu blandit dolor. Vivamus suscipit iaculis erat eu condimentum. Aliquam erat volutpat. Curabitur posuere commodo arcu vel consectetur."),
  new ForumPostEntry("User3", "2 Days ago", 5 , 0 , "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
   new ForumPostEntry("User4", "2 Days ago", 0 , 0 , "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),

  ];




  Future<List<ForumAnswers>> getForumAnswers(String postID) async {

  final response =
     await http.post('http://api/ForumAnswers',
     headers: {"Content-Type": "application/json", 
             'Accept': 'application/json',},
     body: json.encode({'PostID' : postID }));  

 if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON

 List l = json.decode(response.body);
   List<ForumAnswers> posts = l.map((m) => ForumAnswers.fromJson(m)).toList(); 


  return posts;

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

  }


class ForumPostEntry{
  final String username;
  final String hours;
  final int likes;
  final int dislikes;
  final String text;

     ForumPostEntry(this.username, this.hours, this.likes, this.dislikes, this.text);
}

class ForumPost extends StatelessWidget {
  final ForumPostEntry entry;

  ForumPost(this.entry);

  @override
 Widget build(BuildContext context) {
   return new Container(
    margin: const EdgeInsets.only(bottom: 10.0),
    decoration: new BoxDecoration(
      color: Colors.grey,
      borderRadius: const BorderRadius.all(const Radius.circular(20.0)),
     ),
    child: new Column(
      children: <Widget>[
      new Container(
        decoration: new BoxDecoration(
          color: Colors.grey[600],
          borderRadius: const BorderRadius.only(
              topLeft: const Radius.circular(20.0),
              topRight: const Radius.circular(20.0)),
        ),
        child: new Row(
          children: <Widget>[
            new Icon(
              Icons.person,
              size: 50.0,
              color: Colors.white
            ),
            new Expanded(
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  new Text(
                    entry.username
                  ),
                  new Text(
                    entry.hours
                  ),
                ],
              ),
            ),
            new Row(
              children: <Widget>[
                new Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: new Icon(Icons.thumb_up, color: Colors.white),
                ),
                new Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: new Text(entry.likes.toString()),
                ),
                new Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: new Icon(Icons.thumb_down, color: Colors.white),
                ),
                new Padding(
                  padding: const EdgeInsets.only(right: 8.0, left: 2.0),
                  child: new Text(entry.dislikes.toString()),
                ),
              ],
            )
          ],
        ),
      ),
      new Container(
        margin: const EdgeInsets.only(left: 2.0,right: 2.0,bottom: 2.0),
        padding: const EdgeInsets.all(8.0),
        decoration: new BoxDecoration(
          color: Colors.grey[200],
          borderRadius: const BorderRadius.only(bottomLeft :const Radius.circular(20.0),bottomRight :const Radius.circular(20.0))
        ),
        child: new Text(entry.text),
      ),
    ],
    ),
   );
}
 }

  class IconWithText extends StatelessWidget {
 final IconData iconData;
 final String text;
 final Color iconColor;

  IconWithText(this.iconData, this.text, {this.iconColor});
  @override
 Widget build(BuildContext context) {
   return new Container(
    child: new Row(
      children: <Widget>[
        new Icon(
        this.iconData,
        color: this.iconColor,
      ),
      new Padding(
        padding: const EdgeInsets.only(left: 8.0),
        child: new Text(this.text),
      ),
       ],
  ),
    );
 }
 }

2 个答案:

答案 0 :(得分:1)

大概,您的json由最外层的数组组成;放在[..]中。

l,尽管列表恰好包含json.decode,但List<dynamic>的结果将是Map

您应该发现这样做更好:

 List l = json.decode(response.body);
 List<ForumAnswers> posts = l.map((m) => ForumAnswers.fromJson(m)).toList(); 

请注意,如果要返回posts,应将签名更改为返回Future<List<ForumAnswers>>

答案 1 :(得分:0)

使用这些

工厂ForumAnswers.fromJson(地图parsedjson){     返回ForumAnswers(

PATH="$PATH:$HOME/ti/msp430-gcc/bin"
PATH="$PATH:$HOME/ti/msp430-gcc/libexec/gcc/msp430-elf/7.3.1"

如果不遵循这些链接https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51