了解编程作为一个初学者只,在Flutter,是我的编码错误或有一个问题,我的连接,即没有有效的SSL证书?

thtygnil  于 2023-04-13  发布在  Flutter
关注(0)|答案(1)|浏览(89)
import 'package:flutter/material.dart';
import 'package:http/http.dart' as https;
import 'dart:convert';
//above is for import
class Loading extends StatefulWidget {
  const Loading({Key? key}) : super(key: key);
  @override
  State<Loading> createState() => _LoadingState(); //code here
} //code above
//below code
class _LoadingState extends State<Loading> {

  void getTime () async {
  //make the request for timezone from Europe,London
    Uri url = Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London');
    https.Response response = await https.get(url);
    Map data = jsonDecode(response.body);
   // print(data);
//code above
    //get properties from data
    String datetime = ['datetime'] as String;
    String offset = ['offset'] as String;
    print(datetime);
    print(offset);
  }

  @override
  void initState() {
    super.initState();
    getTime();
//code above
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('loading screen'),
    );
  }
}

下面是我的控制台:

Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 1,541ms.
E/flutter (16861): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'List<String>' is not a subtype of type 'String' in type cast
E/flutter (16861): #0      _LoadingState.getTime (package:world_time/pages/loading.dart:22:36)
E/flutter (16861): <asynchronous suspension>
E/flutter (16861):
slsn1g29

slsn1g291#

问题在这里:

String datetime = ['datetime'] as String;
String offset = ['offset'] as String;

你将把一个List([""])赋值给String。

{
    "abbreviation": "BST",
    "client_ip": "223.225.60.61",
    "datetime": "2023-04-12T08:34:34.157770+01:00",
    "day_of_week": 3,
    "day_of_year": 102,
    "dst": true,
    "dst_from": "2023-03-26T01:00:00+00:00",
    "dst_offset": 3600,
    "dst_until": "2023-10-29T01:00:00+00:00",
    "raw_offset": 0,
    "timezone": "Europe/London",
    "unixtime": 1681284874,
    "utc_datetime": "2023-04-12T07:34:34.157770+00:00",
    "utc_offset": "+01:00",
    "week_number": 15
}

另外,在Json响应中没有任何名为“offset”的内容。因此,进行以下更改:

String datetime = data['datetime'];
    String offset = data['dst_offset'];

相关问题