【问题标题】:I can't manage to make an api call using a parsed integer我无法使用解析的整数进行 api 调用
【发布时间】:2020-08-27 08:43:39
【问题描述】:

所以我正在使用颤振构建应用程序,我是颤振新手,需要一些帮助。

因此,就上下文而言,我的应用程序连接到一个 REST API,该 API 与一个虚构的电梯公司的 ruby​​ on rails 网络应用程序相关联(用于学习目的),我想要实现的是改变在我的应用程序中使用文本字段的电梯,我几乎明白了,唯一的事情是,每当我像这样进行 api 调用时:

class DetailScreen extends StatelessWidget {
  // Declare a field that holds the Todo.
  final Elevator elevator;

  // In the constructor, require a Todo.
  DetailScreen({Key key, @required this.elevator}) : super(key: key);

  Future _changeStatus(elevator) async {
    //Fetch the data from the api
    // ignore: non_constant_identifier_names
    var id = elevator.id.toString();
    var holder = id.toString();
    var url = 'https://rocketcrybaby.azurewebsites.net/api/elevators/'+holder;
    var response = await http.put(
        url, body: {'status': '${_statusController.text}'});
    if (_statusController.text != "active"|| _statusController.text != "inactive"){
      return "Error not a valid status !";
    }
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');

    //print(await http.read('https://example.com/foobar.txt'));
   return "sucess";
  }



  @override
  Widget build(BuildContext context) {
    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text("Elevator # " +elevator.id.toString()),
      ),
      body: Center(
        child: Center(
          child: TextField(
            controller: _statusController
          ),
        )
      ),
      floatingActionButton: FloatingActionButton(onPressed: () async => [ await _changeStatus(elevator.id.toString()), print(elevator.status)]),


    );
  }

它返回给我这个错误:

 E/flutter (18441): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance getter 'id'.
E/flutter (18441): Receiver: "3"
E/flutter (18441): Tried calling: id

我真的不知道该怎么做了我尝试了我书中的每一个技巧:/

这里是电梯类的参考

class Elevator {
  final String status;
  final String model;
  final int id;

  Elevator({this.status, this.model, this.id}); //Elevator Constructor

  factory Elevator.fromJson(Map<String, dynamic> json) { //Parse the infos as Json String
    return Elevator(
      status: json['status'],
      model: json['model'],
      id: json['id']
    );
  }


}

另外这是我的 api 中电梯的输出


{
        "id": 3,
        "column_id": 1,
        "serial_number": 7204019747089,
        "model": "Excelium",
        "building_type": "Hybrid",
        "status": "Inactive",
        "date_service_since": "2018-03-09T00:00:00",
        "date_last_inspection": "2019-02-19T00:00:00",
        "inspection_certificate": "Yes",
        "information": "Dori",
        "notes": "Dolores aut et. Ea optio rem. Provident exercitationem ut.",
        "created_at": "2020-04-09T20:41:55",
        "updated_at": "2020-04-09T20:41:55"
    },

【问题讨论】:

    标签: android rest flutter dart mobile


    【解决方案1】:

    解决方案:

    class DetailScreen extends StatelessWidget {
      // Declare a field that holds the Todo.
      final Elevator elevator;
    
      // In the constructor, require a Todo.
      DetailScreen({Key key, @required this.elevator}) : super(key: key);
    
      Future _changeStatus(Elevator  elevator) async {
        //Fetch the data from the api
        // ignore: non_constant_identifier_names
        var id = elevator.id.toString();
        var holder = id.toString();
        var url = 'https://rocketcrybaby.azurewebsites.net/api/elevators/'+holder;
        var response = await http.put(
            url, body: {'status': '${_statusController.text}'});
        if (_statusController.text != "active"|| _statusController.text != "inactive"){
          return "Error not a valid status !";
        }
        print('Response status: ${response.statusCode}');
        print('Response body: ${response.body}');
    
        //print(await http.read('https://example.com/foobar.txt'));
       return "sucess";
      }
    
    
    
      @override
      Widget build(BuildContext context) {
        // Use the Todo to create the UI.
        return Scaffold(
          appBar: AppBar(
            title: Text("Elevator # " +elevator.id.toString()),
          ),
          body: Center(
            child: Center(
              child: TextField(
                controller: _statusController
              ),
            )
          ),
          floatingActionButton: FloatingActionButton(onPressed: () async => [ await _changeStatus(elevator), print(elevator.status)]),
    
    
        );
      }
    

    提示:在声明变量时始终使用变量类型以避免这些错误和良好做法。

    谢谢。

    【讨论】:

      【解决方案2】:

      那是因为您的方法:Future _changeStatus(elevator) async 实际上需要 Elevator elevator,但您提供的是 elevator.id.toString(),这是一个字符串。

      更改方法参数的类型并在FAB的onPressed中更改为等待_changeStatus(elevator)

      【讨论】:

        猜你喜欢
        • 2017-04-06
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        • 2021-10-26
        • 2015-08-07
        • 1970-01-01
        • 2017-08-14
        • 1970-01-01
        相关资源
        最近更新 更多