future 方法在 null - flutter 中被调用

future method was called in null - flutter

我正在获取数据 api 并将其从 Json 转换而来。 我有这种获取数据的方法,打赌在未来的构建器中使用它时它会给我 getPData() 方法被调用为 null。

这是我创建 getPData 方法的地方:

class JsonConnection {
  JsonConnection.jsonDecode();

  static double pLat;
  static double pLong;    
PData timesList;
  Future getPData() async {
    final pos = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.medium);

    pLat = pos.latitude;
    pLong = pos.longitude;
    String date = DateTime.now().toString();
    int method = 4;
    final url = Uri.parse(
        'http://api.aladhan.com/v1/timings/$date?latitude=$pLat&longitude=$pLong&method=$method');
    http.Response res = await http.get(url);
    var data = json.decode(res.body);
    timesList = PData.fromJson(data);
    return timesList;
  }

这里是我使用getPData的地方:

 body: FutureBuilder(
      future: jsonConnection.getPData(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        print("hello");
        print(snapshot.data.meta.timezone);
        if (snapshot.hasData) {
          CircleAvatar();
          return Center(
              child: Container(
                  padding: const EdgeInsets.only(top: 150.0),
                  child: Column(
                    children: [
                      Table(
                        border: TableBorder.all(color: Colors.purpleAccent),
                        defaultColumnWidth: FixedColumnWidth(150.0),
                        defaultVerticalAlignment:
                            TableCellVerticalAlignment.middle,
                        children: <TableRow>[
                          TableRow(
                            children: <Widget>[
                              TableCell(
                                  verticalAlignment:
                                      TableCellVerticalAlignment.middle,
                                  child: Center(
                                    child: Text(snapshot.data.meta.timezone,
                                        style: TextStyle(
                                            color: Colors.black,
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold)),
                                  )),
                         

我能做些什么来解决它?

您是否在终端中测试了 url?您检查过 PData.fromJson 是否正常工作?错误消息很清楚发生了什么。

我已经使用此代码验证了 API,它正在运行:

对于飞镖:

import 'dart:io';

import 'package:wnetworking/wnetworking.dart';

class PlayerTimes {
  static const _url = 'http://api.aladhan.com/v1';

  static Future<Map<String, dynamic>?> fetchTimings({DateTime? date, double? latitude, double? longitude, int method=2, String? tune, int school=0, int midnightMode=0, String? timezonestring, int? latitudeAdjustmentMethod, int? adjustment}) async {
    stdout.write('Fetching timing...');
    
    String eval(String parName, var parValue) => parValue != null ? '&$parName=$parValue' : '';

    var url = '$_url/timings/${date ?? DateTime.now()}?method=$method&school=$school&midnightMode=$midnightMode${eval('latitude', latitude)}${eval('longitude', longitude)}${eval('tune', tune)}${eval('timezonestring', timezonestring)}${eval('latitudeAdjustmentMethod', latitudeAdjustmentMethod)}${eval('adjustment', adjustment)}';
    
    return await HttpReqService
      .getJson<Map<String, dynamic>>(url)
      .then((response) {
        if (response != null) return response['data'] as Map<String, dynamic>;
      })
      .whenComplete(() => print(' done\n'));
  }
}

void main(List<String> args) async {
  print(await PlayerTimes.fetchTimings(latitude:51.508515, longitude:0.1254872));
  print('\nJob done!');
}

结果:

Fetching timing... done

{timings: {Fajr: 03:17, Sunrise: 05:20, Dhuhr: 12:56, Asr: 17:03, Sunset: 20:33, Maghrib: 20:33, Isha: 22:36, Imsak: 03:07, Midnight: 00:56}, date: {readable: 07 May 2021, timestamp: 1620342000, hijri: {date: 25-09-1442, format: DD-MM-YYYY, day: 25, weekday: {en: Al Juma'a, ar: الجمعة}, month: {number: 9, en: Ramaḍān, ar: رَمَضان}, year: 1442, designation: {abbreviated: AH, expanded: Anno Hegirae}, holidays: [Lailat-ul-Qadr]}, gregorian: {date: 07-05-2021, format: DD-MM-YYYY, day: 07, weekday: {en: Friday}, month: {number: 5, en: May}, year: 2021, designation: {abbreviated: AD, expanded: Anno Domini}}}, meta: {latitude: 51.508515, longitude: 0.1254872, timezone: Europe/London, method: {id: 2, name: Islamic Society of North America (ISNA), params: {Fajr: 15, Isha: 15}}, latitudeAdjustmentMethod: ANGLE_BASED, midnightMode: STANDARD, school: STANDARD, offset: {Imsak: 0, Fajr: 0, Sunrise: 0, Dhuhr: 0, Asr: 0, Maghrib: 0, Sunset: 0, Isha: 0, Midnight: 0}}}

Job done!

您可以将 HttpReqService.getJson 替换为典型的 http.get

对于颤振:

import 'package:flutter/material.dart';
import 'package:wnetworking/wnetworking.dart';

class PlayerTimes {
  static const _url = 'https://api.aladhan.com/v1';

  static Future<Map<String, dynamic>?> fetchTimings({DateTime? date, double? latitude, double? longitude, int method=2, String? tune, int school=0, int midnightMode=0, String? timezonestring, int? latitudeAdjustmentMethod, int? adjustment}) async {
    
    String eval(String parName, var parValue) => parValue != null ? '&$parName=$parValue' : '';

    var url = '$_url/timings/${date ?? DateTime.now().millisecondsSinceEpoch}?method=$method&school=$school&midnightMode=$midnightMode${eval('latitude', latitude)}${eval('longitude', longitude)}${eval('tune', tune)}${eval('timezonestring', timezonestring)}${eval('latitudeAdjustmentMethod', latitudeAdjustmentMethod)}${eval('adjustment', adjustment)}';
    
    return await HttpReqService
      .getJson<Map<String, dynamic>>(url)
      .then((response) {
        if (response != null) return response['data'] as Map<String, dynamic>;
      });
  }
}

class HomePage extends StatelessWidget {
  /* ---------------------------------------------------------------------------- */
  const HomePage({Key? key}) : super(key: key);
  /* ---------------------------------------------------------------------------- */
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hi!'),
        centerTitle: true,
      ),
      body: Container(
        child: FutureBuilder<Map<String, dynamic>?>(
          future: PlayerTimes.fetchTimings(latitude:51.508515, longitude:0.1254872),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) return Text(snapshot.error.toString());
              if (snapshot.hasData) return Text(snapshot.data.toString());
              return Text('No Data...');
            }
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

结果: