flutter - 错误 : The operator '[]' isn't defined for the class 'Future<dynamic>'

标签 flutter asynchronous dart

我的天气应用程序出现以下错误。我该如何解决?

编译器信息: lib/loadingscreen.dart:38:41: 错误:未为类“Future”定义运算符“[]”。

  • “ future ”来自“dart:async”。 尝试将运算符更正为现有运算符,或定义“[]”运算符。

String weathericonlink = weatherdata['current']['condition']['icon'];

主文件:

import 'package:flutter/material.dart';

import 'loadingscreen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}

loadingscreen 类是:

import 'dart:async';
import 'dart:convert';

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

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  Future<dynamic> getData() async {
    String url;
    var weatherdata;
    url =
        'https://api.weatherapi.com/v1/current.json?key=${apikey}&q=51.509865,-0.118092';

    http.Response response = await http.get(url);

    if (response.statusCode == 200) {
      String data = response.body;
      weatherdata = jsonDecode(data);
      print(weatherdata);
    } else {
      print(response.statusCode);
    }

    double temp = weatherdata['current']['temp_c'];
    print('Temperature: $temp');

    return weatherdata;
  }

  String getCurrentWeatherIcon() {
    var weatherdata = getData();

    String weathericonlink = weatherdata['current']['condition']['icon'];
    weathericonlink = weathericonlink.substring(35, weathericonlink.length);
    weathericonlink = 'assets/weathericons/$weathericonlink';
    print('Weather icon link : $weathericonlink');

    return weathericonlink;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //getCurrentWeatherIcon();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
      child: Container(
        child: Padding(
          padding: const EdgeInsets.all(32.0),
          child: Column(
            children: <Widget>[
              Text('Hello'),
              Image(
                image: AssetImage('${getCurrentWeatherIcon()}'),
              ),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/weathericons/day/113.png'),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    ));
  }
}

最佳答案

你应该做一些reading Future 是什么以及如何处理它们。

getData 返回一个 Future,而不是您认为的 map 。要从 future 获取 map ,您必须使用 .thenasync-await 处理 future 。

使用await:

Future<String> getCurrentWeatherIcon() async {
  var weatherdata = await getData();

  String weathericonlink = weatherdata['current']['condition']['icon'];
  weathericonlink = weathericonlink.substring(35, weathericonlink.length);
  weathericonlink = 'assets/weathericons/$weathericonlink';
  print('Weather icon link : $weathericonlink');
   
  return weathericonlink;
}

.then:

Future<String> getCurrentWeatherIcon() {
  return getData().then((weatherdata) {
    String weathericonlink = weatherdata['current']['condition']['icon'];
    weathericonlink = weathericonlink.substring(35, weathericonlink.length);
    weathericonlink = 'assets/weathericons/$weathericonlink';
    print('Weather icon link : $weathericonlink');
    return weathericonlink;
  });
}

既然您的 getCurrentWeatherIcon 函数也是一个 future ,您必须使用 FutureBuilder 来显示数据。

Future weatherIcon;

@override
void initState() {
  super.initState();
  weatherIcon = getCurrentWeatherIcon();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: SafeArea(
      child: Container(
        child: Padding(
          padding: const EdgeInsets.all(32.0),
          child: Column(
            children: <Widget>[
              Text('Hello'),
              FutureBuilder(
                future: weatherIcon,
                builder: (context, snapshot) {
                  if(!snapshot.hasData) {
                    return CircularProgressIndicator();
                  }
                  return Image(
                    image: AssetImage(snapshot.data),
                  );
                }
              ),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/weathericons/day/113.png'),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    )
  );
}

关于flutter - 错误 : The operator '[]' isn't defined for the class 'Future<dynamic>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63102427/

相关文章:

flutter - 'Future<Map<String, dynamic>> Function()' 循环中使用的类型 'for' 必须实现 Iterable - Flutter

node.js - nodejs : save function in for loop, 异步问题

dart - 在 Flutter 中检索图像路由

flutter 访问通话记录

listview - 如果只有少量项目,如何使ListView占用空间来填充屏幕

Flutter:Autoroute:RouteGuard 在 AutoTabsScaffold 中不工作

Django异步更新单页模板

flutter - flutter 中的 Future.delayed 与 Timer 有什么区别

flutter - 当应用程序处于后台时,我可以隐藏 Flutter 应用程序内容吗?

javascript - ajax 中的异步和同步 XMLHttpRequest