如何根据api请求将变量获取到文本字段中?

时间:2019-06-04 20:25:21

标签: flutter

我能够发出api请求,并且在我的控制台中我可以正确获得api请求的结果。现在,我想使用结果并在屏幕上显示一些数据。问题是我不知道如何将api结果附加到可以在屏幕上使用的变量。

当创建一个新的flutter项目并使用“从Internet上获取数据”文档时,我可以在屏幕上显示api结果中的内容。然后,在使用此代码并将其集成到我的应用程序后,它将无法正常工作。它仅显示“ return CircularProgressIndicator();”。在屏幕上。

Future<Result> fetchPost() async {
  final response = await http.get(
      'https://maps.googleapis.com/maps/api/place/details/json?    placeid=ChIJYRUMU1blxkcRG7zLfuAzM9I&key=sorry not showing my key in here');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    print('All Good! This link returned status code   ${response.statusCode}');
    debugPrint(response.body);

    return Result.fromJson(json.decode(response.body));

  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

// To parse this JSON data, do
//
//     final result = resultFromJson(jsonString);

Result resultFromJson(String str) =>     Result.fromJson(json.decode(str));

String resultToJson(Result data) => json.encode(data.toJson());

class Result {
  List<dynamic> htmlAttributions;
  ResultClass result;

  Result({
    this.htmlAttributions,
    this.result,
  });

  factory Result.fromJson(Map<String, dynamic> json) => new Result(
        htmlAttributions:
            new List<dynamic>.from(json["html_attributions"].map((x)  => x)),
        result: ResultClass.fromJson(json["result"]),
      );

  Map<String, dynamic> toJson() => {
        "html_attributions":
            new List<dynamic>.from(htmlAttributions.map((x) => x)),
        "result": result.toJson(),
      };
}

//THEN ALL THE CLASSES TO GET THE DATA. debugPrint(response.body);     SHOWS THE WANTED DATA IN THE CONSOLE. THIS PART IS WORKING.
//IN THE CODE BELOW THE FutureBuilder WILL RUN BUT return   CircularProgressIndicator(); IS THE PART THAT IS EXECUTED.


class Home extends StatelessWidget {

  final Future<Result> result;

  Home({Key key, this.result}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: LayoutBuilder(builder: (context, constraint) {
              return new Image.asset(
                'assets/images/Sprokkelbos logo 621x621.jpg',
                fit: BoxFit.contain,
              );
            }),
          ),
          /*
          Expanded(
            flex: 1,
            child: FutureBuilder<Result>(
            future: result,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return     Text(snapshot.data.result.openingHours.periods[1].close.time);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
            ),
          ),
          */

          Expanded(
            flex: 1,
            child: _buildText(
                //text: 'flex: 1', color: Colors.white, textColor: Colors.black),
                text: ('TEST: ')),
          ),

Text(snapshot.data.result.openingHours.periods [1] .close.time);应该给我一个像api结果中一样的值。例如1700代表商店的关闭时间(hhmm)。为什么我得到return CircularProgressIndicator();代替?

运行正常的Flutter文档示例仅包含一个dart文件(仅main.dart)。在我的应用中,代码在第二个屏幕中(不在main.dart中)。

当我替换时,返回CircularProgressIndicator();与返回Text('snapshot.hasData?$ {snapshot.hasData}和snapshot.hasError?$ {snapshot.hasError}');然后我看到两者都是错误的。为什么在快照中没有可用的记录?

0 个答案:

没有答案