簡體   English   中英

LateInitializationError:字段“貨幣”尚未初始化

[英]LateInitializationError: Field 'currencies' has not been initialized

我正在嘗試這個練習項目,但我得到了這個 lateIntialization field not initialized 錯誤我試着讓它們可以為空,但它仍然不起作用。 我嘗試在初始化狀態下對其進行初始化,但它仍然給出相同的錯誤,但它仍然給出未初始化的最新列表貨幣。

接下來我可以嘗試什么?

主要.dart

...
    import 'package:flutter/material.dart';
    import 'package:untitled/services/api_client.dart';
    import 'package:untitled/widgets/drop_down.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    // ignore: use_key_in_widget_constructors
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Homepage(),
        );
      }
    }
    
    class Homepage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<Homepage> {
      ApiClient client = ApiClient();
      Color mainColor = const Color(0xFF212936);
      Color secondColor = const Color(0xFF2849E5);
    
      late List<String> currencies;
      late String from;
      late String to;
    
      late double rate;
      late String result = "";
    
      Future<List<String>> getCurrencyList() async {
        return await client.getCurrencies();
      }
    
      @override
      void initState() {
        (() async {
          List<String> list = await client.getCurrencies();
          setState(() {
            currencies = list;
          });
        });
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: mainColor,
          body: SafeArea(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 18.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // ignore: sized_box_for_whitespace
                  Container(
                    width: 200.0,
                    child: const Text(
                      "Currency Converter",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 36,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Expanded(
                      child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        TextField(
                          onSubmitted: (value) async {
                            rate = (await client.getRate(from, to))!;
                            setState(() {
                              result =
                                  (rate * double.parse(value)).toStringAsFixed(3);
                            });
                          },
                          decoration: InputDecoration(
                              filled: true,
                              fillColor: Colors.white,
                              labelText: "Input value to convert",
                              labelStyle: TextStyle(
                                fontWeight: FontWeight.normal,
                                fontSize: 18.0,
                                color: secondColor,
                              )),
                          style: const TextStyle(
                            color: Colors.black,
                            fontSize: 24.0,
                            fontWeight: FontWeight.bold,
                          ),
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                        ),
                        const SizedBox(
                          height: 20.0,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          // ignore: prefer_const_literals_to_create_immutables
                          children: [
                            customDropDown(currencies, from, (val) {
                              setState(() {
                                from = val;
                              });
                            }),
                            FloatingActionButton(
                              onPressed: () {
                                String temp = from;
                                setState(() {
                                  from = to;
                                  to = temp;
                                });
                              },
                              // ignore: sort_child_properties_last
                              child: const Icon(Icons.swap_horiz),
                              elevation: 0.0,
                              backgroundColor: secondColor,
                            ),
                            customDropDown(currencies, to, (val) {
                              setState(() {
                                to = val;
                              });
                            }),
                          ],
                        ),
                        const SizedBox(height: 50.0),
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(16.0),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(16.0),
                          ),
                          child: Column(
                            children: [
                              const Text("Result",
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 24.0,
                                    fontWeight: FontWeight.bold,
                                  )),
                              Text(result,
                                  style: TextStyle(
                                    color: secondColor,
                                    fontSize: 36.0,
                                    fontWeight: FontWeight.bold,
                                  )),
                            ],
                          ),
                        )
                      ],
                    ),
                  ))
                ],
              ),
            ),
          ),
        );
      }
    }


    import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    class ApiClient {
      final Uri currncyURL = Uri.https(
        "api.fastforex.io",
        "/currencies",
        {"apiKey": "e64cd89c61-88ad358143-rcu0bj"},
      );
      Future<List<String>> getCurrencies() async {
        http.Response res = await http.get(currncyURL);
        if (res.statusCode == 200) {
          var body = jsonDecode(res.body);
          var list = body["currencies"];
          List<String> currencies = (list.keys).toList();
          print(currencies);
          return currencies;
        } else {
          throw Exception("Failed to connect to API");
        }
      }
    
      Future<double>? getRate(String from, String to) async {
        final Uri rateUrl = Uri.https("api.fastforex.io", "/currencies", {
          "apiKey": "e64cd89c61-88ad358143-rcu0bj",
          "q": "${from}_${to}",
          "compact": "ultra"
        });
        http.Response res = await http.get(rateUrl);
        if (res.statusCode == 200) {
          var body = jsonDecode(res.body);
          // ignore: unnecessary_brace_in_string_interps
          return body["${from}_${to}"];
        } else {
          throw Exception("Failed to connect to API");
        }
      }
    }
...

您在初始化之前引用了“貨幣”列表。 您必須等到它被 ApiClient 響應初始化。 如果列表為空,只需在 UI 中編寫一個條件以不構建相關小部件。 (對於這種方法,貨幣列表應該可以為空,因為后期字段不能用於空檢查)

if(currencies!=null)...[
        customDropDown(currencies, to, (val) {
            setState(() {
              to = val;
            });
        }),
 ],

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM