【问题标题】:How to display Future result (error) in Flutter如何在 Flutter 中显示 Future 结果(错误)
【发布时间】:2021-11-10 20:25:32
【问题描述】:

我正在尝试使用 Places API 构建地址搜索。但我不知道如何显示结果。

搜索字段类

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:loci/services/place_service.dart';

class addressSearch extends SearchDelegate<Suggestion> {

  searchAddress(sessionToken) {
  apiClient = PlaceApiProvider(sessionToken);
  }
  PlaceApiProvider? apiClient;

@override
  List<Widget>? buildActions(BuildContext context) {
    // TODO: implement buildActions
    return [
      IconButton(
        onPressed: (){
          query = '';
        }, 
        icon: Icon(Icons.clear))
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    return 
      IconButton(
        onPressed: (){
          //close(context, null);
        }, 
        icon: Icon(Icons.arrow_back));
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return Center(child: Text("Adresse nicht gefunden"));
  }

  PlaceApiProvider result = PlaceApiProvider(Client);
  @override
  Widget buildSuggestions(BuildContext context) {
    print('counter value :');
    final PlaceApiProvider requests = PlaceApiProvider(PlaceApiProvider);
    // TODO: implement buildSuggestions
    return FutureBuilder(
      future: query == ""
          ? null
          : result.fetchSuggestions(),
      builder: (context, snapshot) => query == ''
      ? Container(
        padding: EdgeInsets.all(16),
        child: Text("Gib deine Unternehmensadresse an"),
      )
      : snapshot.hasData
        ? ListView.builder(
          itemBuilder: (context, index) => ListTile(
          //data = snapshot.data[index] as Suggestion;
            //Data return here
            title: Text((snapshot.data[index] as Suggestion).description), 
            onTap: () {
              close(context, snapshot.data as Suggestion);
            },
            
          ),
          itemCount: (snapshot.data as dynamic).length,
          )
          : Center(child: Text('lädt...')),
    );
  }
}

但颤振标记“[index]”的左括号说:

方法 []' 不能被无条件调用,因为接收者 可以为“空”

title: Text((snapshot.data[index] as Suggestion).description),

如果我将其更改为: title: Text((snapshot.data?[index] as Suggestion).description), 颤动说:

没有为类型“object”定义运算符“[]”。尝试定义 运算符'[]'

API 调用类

import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:http/http.dart';

class Suggestion {
  final String placeId;
  final String description;

  Suggestion(this.placeId, this.description);


  @override
  String toString() {
    return 'Suggestion(description: $description, placeId: $placeId';
  }
}

class PlaceApiProvider {
  final client = new Client();

  PlaceApiProvider(this.sessionToken);

  final sessionToken;

  // static final String androidKey = 'XYZ';
  // static final String iosKey = 'XYZ';
  // final apiKey =  Platform.isAndroid ? androidKey : iosKey;
  
  Future<List<Suggestion>> fetchSuggestions() async {
    print('counter value : RESPONSE');
    const request = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=TEST&types=address&components=country:de&key=XYZ';
    final response = await client.get(Uri.parse(request));

    if (response.statusCode == 200) {
      final result = json.decode(response.body);
      if (result['status'] == 'OK') {
          
        //Compose Suggestions in a List
        return result['predictions']
         .map<Suggestion>((p) => Suggestion(p['place_id'], p['description']))
         .toList();
      }
      if (result['status'] == 'ZERO_RESULTS') {
          print('keine ergebnisse');
        return [];
      }
          print('error');
      throw Exception(result['error_message']);
    } else {
          print('fehler beim laden');
      throw Exception('Failed to fetch suggestion');
    }
   // throw ArgumentError.notNull();
  }


}```

The API does work and returns a json, but I don't know how to get the descriptions or the placeId. 

I am on this for days and would be so thankful if somebody can help me.

【问题讨论】:

    标签: json flutter google-places-api flutter-futurebuilder flutter-http


    【解决方案1】:

    你需要做的是:

    final suggestion = snapshot.data as Suggestion?;
    

    你没有地方写这一行的原因是代码写得不好。通过将其分解为小部件来重构它,编写精美的“if”语句,然后找出问题所在。

    【讨论】:

    • 我重新编码了构建器,现在它可以工作了。 (我什至没有添加新代码)我爱你
    猜你喜欢
    • 2019-08-28
    • 2019-11-07
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 2020-04-25
    • 2021-10-09
    • 2018-11-13
    • 2018-09-28
    相关资源
    最近更新 更多