Flutter FutureBuilder和ListTile创建

时间:2020-07-25 14:37:48

标签: flutter flutter-layout flutter-dependencies

我已经写了下面的代码。它的作用是,使用REST API将其连接到服务器,并下达订单。作为回报,我得到以下JSON响应:

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

每次我按下“提高按钮”时,它都会连接到服务器并创建一个新订单,并每次都为我提供一个新订单UUID,并在Text Widget中显示。我想要实现的是调用FutureBuilder或ListViewBuilder,这样,每当我按下“提高按钮”时,都会触发该构建器,并且ListTile(或Container)将出现,其中包含新的订单UUID。

例如,如果我按4次“提升按钮”,我希望我的UI显示4个ListTile(或Container),每个ListTile具有唯一的订单UUID。我尝试寻找解决方案,但没有走运。我是Flutter的新手,我才刚刚开始学习它。

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'model/orderTaxi_model.dart';
import 'package:http/http.dart' as http;


class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
Future<OrderTaxi> _createOrder(String phone) async {
  final http.Response response = await http.post(
    'http://XXXXXXXXXXXXX/api/order',
    headers: <String, String>{
    },
    body: <String, String>{
      'api_key': 'XXXXXXXXXXXXXXXXXX',
      'phone': phone,
      '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');
  }
}


class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  OrderTaxi _futureOrder;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Post Request'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          
          TextField(
            controller: _controller,
          ),
          RaisedButton(
            child: Text('Place Order'),
            onPressed: () async {
              final String phone = _controller.text;
              OrderTaxi response = await _createOrder(phone);
              setState(() {
                _futureOrder = response;
              });
            },
          ),
          _futureOrder == null? Container(): Text('${_futureOrder.uuid}'),
        ],
      )
    );
  }

}

0 个答案:

没有答案