Flutter POST 和 GET 请求组合

问题描述 投票:0回答:2

我想创建一个应用程序来订购出租车。当我下订单时,我想在 ListView 中显示一张卡片。在后台,我有两个请求正在进行。第一个请求是 POST 请求,我在其中下了出租车订单。第二个请求是 GET 请求,我想在其中检索有关订单的信息(剩余时间等)。

POST 请求的响应如下:

{"status": "DONE", "response": {"message": "Your order saved.", "uuid": "fc1d6f52-9aef-11e3-84ae-0015af9e1aa1"}}

GET 请求的响应如下:

{"status": "DONE", "response": {"status": 100, "message": "Заказ выполнен", "driver_id": "d1", "start_time": "2014-08-26 18:15:00", "remaining_time": "5", "amount": 150.00, "rate_id": 1}}

该过程应该按以下方式进行(这就是我的想法)。首先,通过 POST 请求,我下订单并获得 UUID 作为响应。然后我必须使用 UUID(来自 POST 请求)并将其放入 GET 函数中,以便根据唯一的 UUID,我获取订单信息。下面我发布了我遇到的错误,我被困在这一点上。任何帮助将不胜感激。我是 Flutter 新手,也许我遗漏了一些要点或概念。

import 'package:flutter/material.dart';
import 'package:xfit/model/orderTaxi_model.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

class DemoRequest extends StatefulWidget {
  @override
  _DemoRequestState createState() => _DemoRequestState();
}





class _DemoRequestState extends State<DemoRequest> {
  var _listSection = List<Widget>();
  OrderTaxi _futureOrder;
  String info;

  Future<OrderTaxi> _createOrder() async {
    final http.Response response = await http.post(
      'http://xxx.xxx/api/order',
      headers: <String, String>{
      },
      body: <String, String>{
        'api_key': 'XXXX-XXXX-XXXX-XXXX',
        'phone': '1111',
        'street': 'Testttt',
        'moderation_required': 'yes',
      },
    );
    if (response.statusCode == 200) {
      final Map responseString = jsonDecode(response.body);
      print(responseString);
      return OrderTaxi.fromJson(responseString);
    } else {
      throw Exception('Failed to create order');
    }
  }

  Future<String> getOrderInfo() async {
    var response = await http.get('http://xx.xxx/api/order/?api_key=XXXX-XXXX-XXXX-XXXX&uuid=${_futureOrder.uuid.toString()}');
    setState(() {
      var extractedInfo = json.decode(response.body);

      info = extractedInfo['response']['message'];
    });
    print(info);

  }

  @override
  void initState() {
    super.initState();
    _listSection.add(listSectionMethod('Title 1', 'Hello I am subtitle one', Icons.forward));
    _listSection.add(listSectionMethod('Title 2', 'Hello I am subtitle two', Icons.forward));

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Trial #1'),
        centerTitle: true,
      ),
      body: listSection(),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          OrderTaxi response = await _createOrder();
          await getOrderInfo();
          setState(()  {
            // Here we add a new item to the list
            _futureOrder = response;
             _listSection.add(
             listSectionMethod('Order Status is: ', info, Icons.forward),
            );
          });
        },
        child: Icon(Icons.add),
        backgroundColor: Colors.blue,
      ),
    );
  }
  Card listSectionMethod(String title, String subtitle, IconData icon) {
    return new Card(
      child: ListTile(
        title: Text(
          title,
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Text(subtitle),
        trailing: Icon(
          icon,
          color: Colors.blue,
        ),
      ),
    );
  }
  Widget listSection() {
    return Container(
      margin: EdgeInsets.only(top: 20),
      child: ListView(
        children: [
          Column(
            children: this._listSection, // ----> Add this

          ),
        ],
      ),
    );
  }
}

这是我收到的错误:

E/flutter ( 4465): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 4465): Receiver: null
E/flutter ( 4465): Tried calling: []("message")
E/flutter ( 4465): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter ( 4465): #1      _DemoRequestState.getOrderInfo.<anonymous closure> (package:xfit/getRequest_tutorial.dart:66:39)
E/flutter ( 4465): #2      State.setState (package:flutter/src/widgets/framework.dart:1233:30)
E/flutter ( 4465): #3      _DemoRequestState.getOrderInfo (package:xfit/getRequest_tutorial.dart:63:5)
E/flutter ( 4465): <asynchronous suspension>
E/flutter ( 4465): #4      _DemoRequestState.build.<anonymous closure> (package:xfit/getRequest_tutorial.dart:90:17)
E/flutter ( 4465): #5      _DemoRequestState.build.<anonymous closure> (package:xfit/getRequest_tutorial.dart:88:20)
E/flutter ( 4465): #6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
E/flutter ( 4465): #7      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
E/flutter ( 4465): #8      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter ( 4465): #9      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
E/flutter ( 4465): #10     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5)
E/flutter ( 4465): #11     BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7)
E/flutter ( 4465): #12     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter ( 4465): #13     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter ( 4465): #14     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
E/flutter ( 4465): #15     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter ( 4465): #16     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
E/flutter ( 4465): #17     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
E/flutter ( 4465): #18     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter ( 4465): #19     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter ( 4465): #20     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter ( 4465): #21     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter ( 4465): #22     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter ( 4465): #23     _rootRunUnary (dart:async/zone.dart:1196:13)
E/flutter ( 4465): #24     _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter ( 4465): #25     _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter ( 4465): #26     _invoke1 (dart:ui/hooks.dart:275:10)
E/flutter ( 4465): #27     _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)
E/flutter ( 4465): 
I/flutter ( 4465): 0b6eb2b2-2edd-4b28-9fdd-fec2e28530b0
entity-framework flutter flutter-layout flutter-dependencies
2个回答
0
投票
Updated Code:


import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

class DemoRequest extends StatefulWidget {
  @override
  _DemoRequestState createState() => _DemoRequestState();
}

class _DemoRequestState extends State<DemoRequest> {
  var _listSection = List<Widget>();
  OrderTaxi _futureOrder;
  String info = "No information available";

  Future<OrderTaxi> _createOrder() async {
    try {
      final http.Response response = await http.post(
        'http://xxx.xxx/api/order',
        headers: <String, String>{
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'api_key': 'XXXX-XXXX-XXXX-XXXX',
          'phone': '1111',
          'street': 'Testttt',
          'moderation_required': 'yes',
        }),
      );

      if (response.statusCode == 200) {
        final Map<String, dynamic> responseString = jsonDecode(response.body);
        print(responseString);
        return OrderTaxi.fromJson(responseString);
      } else {
        throw Exception('Failed to create order');
      }
    } catch (e) {
      print(e);
      throw Exception('Error occurred while creating order');
    }
  }

  Future<void> getOrderInfo() async {
    if (_futureOrder != null && _futureOrder.uuid != null) {
      try {
        var response = await http.get(
          'http://xx.xxx/api/order/?api_key=XXXX-XXXX-XXXX-XXXX&uuid=${_futureOrder.uuid.toString()}',
        );

        if (response.statusCode == 200) {
          var extractedInfo = json.decode(response.body);
          setState(() {
            info = extractedInfo['response']?['message'] ?? 'No message found';
          });
          print(info);
        } else {
          setState(() {
            info = 'Failed to retrieve order info';
          });
        }
      } catch (e) {
        print(e);
        setState(() {
          info = 'Error occurred while fetching order info';
        });
      }
    } else {
      setState(() {
        info = 'Order UUID is not available yet';
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _listSection.add(listSectionMethod('Title 1', 'Hello I am subtitle one', Icons.forward));
    _listSection.add(listSectionMethod('Title 2', 'Hello I am subtitle two', Icons.forward));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Trial #1'),
        centerTitle: true,
      ),
      body: listSection(),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          try {
            OrderTaxi response = await _createOrder();
            setState(() {
              _futureOrder = response; // Set the created order first
            });
            await getOrderInfo(); // Fetch order info after order is created
            setState(() {
              _listSection.add(
                listSectionMethod('Order Status is: ', info, Icons.forward),
              );
            });
          } catch (e) {
            print(e);
            // Handle errors in creating order or fetching order info
          }
        },
        child: Icon(Icons.add),
        backgroundColor: Colors.blue,
      ),
    );
  }

  Card listSectionMethod(String title, String subtitle, IconData icon) {
    return new Card(
      child: ListTile(
        title: Text(
          title,
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Text(subtitle),
        trailing: Icon(
          icon,
          color: Colors.blue,
        ),
      ),
    );
  }

  Widget listSection() {
    return Container(
      margin: EdgeInsets.only(top: 20),
      child: ListView(
        children: [
          Column(
            children: this._listSection, // ----> Add this
          ),
        ],
      ),
    );
  }
}

class OrderTaxi {
  String uuid;

  OrderTaxi({this.uuid});

  factory OrderTaxi.fromJson(Map<String, dynamic> json) {
    return OrderTaxi(uuid: json['response']['uuid']);
  }
}

-1
投票

这可能是答案:stackoverflow.com/a/51473337/6942599 问题是模拟器。

© www.soinside.com 2019 - 2024. All rights reserved.