http - 加载时间长,并且显示_InternalLinkedHashMap和列表<Dynamic>错误

标签 http flutter dart

当iam试图解析显示错误消息的数据时。

“类'_InternalLinkedHashMap'没有实例获取程序'menuName'。接收者:_LinkedHashMap len:7尝试调用:menuName”。

在我的小部件构建中,它正在返回脚手架

     body: new Container(
        alignment: Alignment.center,
        child: new Column(
        children: [

          new ListTile(
                title: Row(
                    children: <Widget>[
                      new Expanded(child: new Text("Shop" ,style: new TextStyle(fontSize: 11.0,),)),
                      new Expanded(child: new Text("Sales",style: new TextStyle(fontSize: 11.0,),)),
                      new Expanded(child: new Text("Damage",style: new TextStyle(fontSize: 11.0,),)),

                    ]
                ),
              ),




              Expanded(child: FutureBuilder<Menu>(
                  future: fetchData(),
                  builder: (context, snapshot) {
                   if (snapshot.hasData) {
                      final List<MenuCol> data = snapshot.data.menuCol;
                        return ListView(
                        children:<Widget>[ 
                        new Expanded(
                        child: ListView.builder(
                        itemCount: data == null ? 0 : data.length,
                        itemBuilder: (BuildContext context, int index) {
                        return Container(
                        height: 50,
                          color: Colors.amber[100],
                          child: ListTile(                //return new ListTile(
                            onTap: null,
                            title: Row(
                              children: <Widget>[
                              Expanded(child: new InkWell(
                                child: new Text(data[index].menuName),
                                onTap: _detailView(),
                              )),
                              Expanded(child: Text(data[index].menuID)),
                              Expanded(child: Text(data[index].menuKEY)),
                              ]
                            )
                          ),

                        );
                        }, //itemBuilder

                      ),


                        ),
                        ],
                      );
                    } 
                    else if (snapshot.hasError) {
                      return Text("TEST "+snapshot.hasError.toString());
                    }
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  },

              ),

.............
Future<Menu> fetchData() async {
  final http.Response response = await http.post('http://',  headers: <String, String>{  'Content-Type': 'application/json; charset=UTF-8',  },  body: jsonEncode(<String, String>{ 'DevID': "12333", }), );

if (response.statusCode== 200) {

  final parsed = jsonDecode(response.body);
  return Menu.fromJson(parsed); 

} else {
  throw Exception('Failed to create album.');
}

 }


JSON DATA 

我创建了一个名为Menu和MenuCol的类,我需要在扩展的列表 View 中显示menucol中的数据
 {
   "PassKey": "Y",    
   "UsrID": "",
   "MenuCol": [
     {

        "MenuID": "51806",
        "MenuName": "test",
        "MenuKEY": "t1",

    }
]}

最佳答案

您可以在下面复制粘贴运行完整代码
您可以查看完整代码的Menu类定义以获取详细信息
您可以使用menuFromJson

Menu menuFromJson(String str) => Menu.fromJson(json.decode(str));
...
if (response.statusCode == 200) {
      Menu menu = menuFromJson(response.body);
      return menu;
    }

工作演示

enter image description here

完整的代码
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Menu menuFromJson(String str) => Menu.fromJson(json.decode(str));

String menuToJson(Menu data) => json.encode(data.toJson());

class Menu {
  Menu({
    this.passKey,
    this.devId,
    this.errorMsg,
    this.usrId,
    this.menuCol,
  });

  String passKey;
  String devId;
  String errorMsg;
  String usrId;
  List<MenuCol> menuCol;

  factory Menu.fromJson(Map<String, dynamic> json) => Menu(
        passKey: json["PassKey"],
        devId: json["DevID"],
        errorMsg: json["ErrorMsg"],
        usrId: json["UsrID"],
        menuCol:
            List<MenuCol>.from(json["MenuCol"].map((x) => MenuCol.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "PassKey": passKey,
        "DevID": devId,
        "ErrorMsg": errorMsg,
        "UsrID": usrId,
        "MenuCol": List<dynamic>.from(menuCol.map((x) => x.toJson())),
      };
}

class MenuCol {
  MenuCol({
    this.devId,
    this.passKey,
    this.errorMsg,
    this.menuId,
    this.menuName,
    this.menuKey,
    this.userId,
  });

  String devId;
  String passKey;
  String errorMsg;
  String menuId;
  String menuName;
  String menuKey;
  String userId;

  factory MenuCol.fromJson(Map<String, dynamic> json) => MenuCol(
        devId: json["DevID"],
        passKey: json["PassKey"],
        errorMsg: json["ErrorMsg"],
        menuId: json["MenuID"],
        menuName: json["MenuName"],
        menuKey: json["MenuKEY"],
        userId: json["UserID"],
      );

  Map<String, dynamic> toJson() => {
        "DevID": devId,
        "PassKey": passKey,
        "ErrorMsg": errorMsg,
        "MenuID": menuId,
        "MenuName": menuName,
        "MenuKEY": menuKey,
        "UserID": userId,
      };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<Menu> _future;

  Future<Menu> fetchData() async {
    String jsonString = r'''
    {
   "PassKey": "Y",
   "DevID": "",
   "ErrorMsg": "",
   "UsrID": "",
   "MenuCol": [
     {
        "DevID": "",
        "PassKey": "",
        "ErrorMsg": "",
        "MenuID": "51806",
        "MenuName": "test",
        "MenuKEY": "t1",
        "UserID": ""
    },
    {
        "DevID": "",
        "PassKey": "",
        "ErrorMsg": "",
        "MenuID": "51807",
        "MenuName": "test2",
        "MenuKEY": "t2",
        "UserID": ""
    }
]}
    ''';

    var response = http.Response(jsonString, 200);
    if (response.statusCode == 200) {
      Menu menu = menuFromJson(response.body);
      return menu;
    } else {
      throw Exception('Error collecting the data');
    }
  }

  @override
  void initState() {
    _future = fetchData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container(
          alignment: Alignment.center,
          child: Column(
            children: [
              ListTile(
                title: Row(children: <Widget>[
                  Expanded(
                      child: Text(
                    "Shop",
                    style: TextStyle(
                      fontSize: 11.0,
                    ),
                  )),
                  Expanded(
                      child: Text(
                    "Sales",
                    style: TextStyle(
                      fontSize: 11.0,
                    ),
                  )),
                  Expanded(
                      child: Text(
                    "Damage",
                    style: TextStyle(
                      fontSize: 11.0,
                    ),
                  )),
                ]),
              ),
              FutureBuilder(
                  future: _future,
                  builder: (context, AsyncSnapshot<Menu> snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.none:
                        return Text('none');
                      case ConnectionState.waiting:
                        return Center(child: CircularProgressIndicator());
                      case ConnectionState.active:
                        return Text('');
                      case ConnectionState.done:
                        if (snapshot.hasError) {
                          return Text(
                            '${snapshot.error}',
                            style: TextStyle(color: Colors.red),
                          );
                        } else {
                          final List<MenuCol> data = snapshot.data.menuCol;
                          return Expanded(
                              child: ListView.builder(
                            itemCount: data == null ? 0 : data.length,
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                height: 50,
                                color: Colors.amber[100],
                                child: ListTile(
                                    //return  ListTile(
                                    onTap: null,
                                    title: Row(children: <Widget>[
                                      Expanded(
                                          child: InkWell(
                                        child: Text(data[index].menuName),
                                        //onTap: _detailView(),
                                      )),
                                      Expanded(child: Text(data[index].menuId)),
                                      Expanded(
                                          child: Text(data[index].menuKey)),
                                    ])),
                              );
                            }, //itemBuilder
                          ));
                        }
                    }
                  }),
            ],
          ),
        ));
  }
}

关于http - 加载时间长,并且显示_InternalLinkedHashMap和列表<Dynamic>错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62383240/

相关文章:

keyboard - 当键盘出现时,Flutter 小部件会调整大小。如何防止这种情况?

flutter - 使用loadingBuilder时未显示Flutter Image.network?

rest - 不允许对 Tomcat 服务器的 ExtJS PUT 请求

python - Python/Mechanize 中的 Http 错误 405/500(使用 mechanize 自动登录一个网站)

flutter 逻辑问题

firebase - 类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型转换中类型 'TodoModel' 的子类型

flutter - 如何改变按钮主题的背景颜色,文本颜色和高度?

python - elasticsearch-py搜索查询比等效的curl慢得多

httpconnection.getResponseCode() 给出 EOF 异常

php - Dart 与 PHP 代码中的不同哈希结果