【问题标题】:Error: The operator '[]' isn't defined for the class 'Future<dynamic>'错误:未为类“Future<dynamic>”定义运算符“[]”
【发布时间】:2020-11-16 00:33:06
【问题描述】:

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

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

  • “未来”来自“飞镖:异步”。 尝试将运算符更正为现有运算符,或定义“[]”运算符。

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(),
    );
  }
}

加载屏幕类是:

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,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    ));
  }
}

【问题讨论】:

    标签: flutter asynchronous dart


    【解决方案1】:

    您应该对reading 了解Future 是什么以及如何处理它们。

    getData 返回 Future,而不是您认为的映射。要从未来获取地图,您必须使用.thenasync-await 处理未来。

    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 函数也是未来,您必须使用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,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        )
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 2020-03-05
      • 2020-02-15
      • 2023-01-05
      • 2021-07-31
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多