Flutter JSON数据问题

Posted

技术标签:

【中文标题】Flutter JSON数据问题【英文标题】:Flutter JSON data issue 【发布时间】:2020-12-31 23:05:37 【问题描述】:

我在从 Flutter 移动应用程序中获取 json 数据时遇到问题。

代码如下:

import 'package:flutter/material.dart';
import 'package:flutter_app/pages/main_page.dart';


class App extends StatelessWidget

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Flutter NodeJS",
      home: MainPage(),
    );
  

void main()
  runApp(App());

main_page.dart


import 'package:flutter/material.dart';
import 'package:flutter_app/modules/http.dart';
import 'package:flutter_app/pages/add_user_page.dart';

class MainPage extends StatefulWidget

  @override
  State<StatefulWidget> createState() 
    return MainPageState();
  

class User

  String id;
  String first_name,email;
  User(this.id, this.first_name,this.email);

class MainPageState extends State<MainPage>

  List<User> users = [];
  Future<void> refreshUsers()async
    var result = await http_get('users');
    if(result.ok)
    
      setState(() 
        users.clear();
        var in_users = result.data as List<dynamic>;
        in_users.forEach((in_user)
          users.add(User(
            in_user['id'].toString(),
              in_user['first_name'],
              in_user['email']
          ));
        );
      );
    
  
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        title: Text("Users"),
        //email: Text("Email"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: ()
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context)
                  return AddUserPage();
                
              ));
            ,
          )
        ],
      ),
      body: RefreshIndicator(

        onRefresh: refreshUsers,
        child: ListView.separated(
          itemCount: users.length,
          itemBuilder: (context, i) => ListTile(
            leading: Icon(Icons.person),
            title: Text(users[i].first_name+"\n" + users[i].email),
            //email: Text(users[i].email),
          ),
          separatorBuilder: (context, i) => Divider(),
        ),
      ),
    );
  

http.dart

import 'dart:convert';

import "package:http/http.dart" as http;

class RequestResult

  bool ok;
  dynamic data;
  RequestResult(this.ok, this.data);

//'https://jsonplaceholder.typicode.com/users/1
//http://192.168.183.179:8081/api/users/
const PROTOCOL = "http";
const DOMAIN = "https://jsonplaceholder.typicode.com/users/1";

Future<RequestResult> http_get(String route, [dynamic data]) async

  var dataStr = jsonEncode(data);
  var url = "$PROTOCOL://$DOMAIN/$route?data=$dataStr";
  var result = await http.get(url);
  return RequestResult(true, jsonDecode(result.body));

Future<RequestResult> http_post(String route, [dynamic data]) async

  var url = "$PROTOCOL://$DOMAIN/$route";
  var dataStr = jsonEncode(data);
  var result = await http.post(url, body: dataStr, headers:"Content-Type":"application/json");
  return RequestResult(true, jsonDecode(result.body));

当我从“https://jsonplaceholder.typicode.com/users/1”获取 json 数据时。它工作正常。 enter image description here

当我尝试从“https://192.168.183.179:8081/api/users”获取 json 数据时。它给出错误:

在 Object.createErrorWithStack (http://localhost:15340/dart_sdk.js:4348:12) 在 Object._rethrow (http://localhost:15340/dart_sdk.js:37892:16) 在 async._AsyncCallbackEntry.new.callback (http://localhost:15340/dart_sdk.js:37886:13) 在 Object._microtaskLoop (http://localhost:15340/dart_sdk.js:37718:13) 在 _startMicrotaskLoop (http://localhost:15340/dart_sdk.js:37724:13) 在 http://localhost:15340/dart_sdk.js:33243:9

我做错了什么

问候, SAO

【问题讨论】:

【参考方案1】:

在 Postman 中检查 ip 地址是否在返回数据。

另一种情况是获取的数据无法正确传输到应用程序。检查存储数据的变量和类型。

【讨论】:

以上是关于Flutter JSON数据问题的主要内容,如果未能解决你的问题,请参考以下文章

Flutter 索引 Json 数据

Flutter:从 json 列表中获取数据

如何在flutter中本地获取json文件中的json数据

在 Flutter 中提取 JSON 数据时遇到问题

Flutter:JSON数据,列表下列表

Flutter 中的 JSON 数据解析