如何将下拉菜单项字符串传递给fetchData()Json对象

时间:2018-07-02 19:12:36

标签: flutter flutter-layout

我想将所选下拉货币项目的String值传递给
 fetchPost()使用初始化的字符串selectedSymbol的Future函数,但是返回空的Point Value。我试图将SelectedCurrency实例传递给selectedSymbol,但是它显示nullPointException。这是代码:

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


    void main() => runApp(
      MaterialApp(
        title: 'Birr Converter App',
        home: MainClass(),
      ),
    );


    class User {
      User(this.name);
      final String name;
          }

    class CurrencyClass {
      final String currencyType;
      CurrencyClass(this.currencyType);
      }

   class MainClass extends StatelessWidget {
     @override
      Widget build(BuildContext context) {
       return Scaffold(
        body: ConverterParent(),
       );
    // TODO: implement build
      }
     }

    class ConverterParent extends StatefulWidget {
       @override
       _ConversionHouse createState() => _ConversionHouse();
       }

    class _ConversionHouse extends State<ConverterParent> {
       User selectedLanguage;
       String selectedSymbol ;
       CurrencyClass selectedCurrency;
       double exchangeData = 0.0;
       Text birrName = Text('Birr',style: TextStyle(fontSize: 30.0),);
       Text convertedAmount = Text('0.00');
       Text convertText = Text('Convert', style: TextStyle(color: Colors.white, 
       fontSize: 25.0),);
       final myController = TextEditingController();
       List<User> users = <User>[
          User('English'),
          User('Amharic'),
          User('Oromigna'),
          User('Tigrigna'),
          User('Somali')
         ];
       List<CurrencyClass> currency = <CurrencyClass>[
         CurrencyClass('USD'),
         CurrencyClass('GBP'),
         CurrencyClass('CAD'),
         CurrencyClass('EUR'),
         CurrencyClass('AUD'),
         CurrencyClass('SAD'),
         CurrencyClass('KAD'),
          ];

     @override
      void initState() {
       super.initState();
       selectedLanguage = users[0];
       this.fetchPost();
    }

    @override
     void dispose() {
      myController.dispose();
      super.dispose();
    }


     @override
      Widget build(BuildContext context) {
       return Scaffold(
        appBar: AppBar(
        title: Text('Birr Converter'),
        backgroundColor: Colors.white10,
        actions: <Widget>[
          DropdownButton<User>(
            value: selectedLanguage,
            onChanged: (User newValue) {
              setState(() {
                selectedLanguage = newValue;
                if (newValue == users[0]) {
                  currency = <CurrencyClass>[
                    CurrencyClass('ENG'),
                    CurrencyClass('GBP'),
                    CurrencyClass('CAD'),
                    CurrencyClass('EUR'),
                    CurrencyClass('AUD'),
                    CurrencyClass('SAD'),
                    CurrencyClass('KAD'),
                  ];
                  birrName = Text(
                    'Birr',
                    style: TextStyle(fontSize: 30.0),
                  );
                  convertText = Text(
                    'Convert',
                    style: TextStyle(fontSize: 30.0, color: Colors.white),
                  );
                } else if (newValue == users[1]) {
                  currency = <CurrencyClass>[
                    CurrencyClass('AMH'),
                    CurrencyClass('GBP'),
                    CurrencyClass('CAD'),
                    CurrencyClass('EUR'),
                    CurrencyClass('AUD'),
                    CurrencyClass('SAD'),
                    CurrencyClass('KAD'),
                  ];
                  birrName = Text(
                    'Sop',
                    style: TextStyle(fontSize: 30.0),
                  );
                  convertText = Text(
                    'Lewet',
                    style: TextStyle(fontSize: 30.0, color: Colors.white),
                  );
                } else if (newValue == users[2]) {
                  currency = <CurrencyClass>[
                    CurrencyClass('ORO'),
                    CurrencyClass('GBP'),
                    CurrencyClass('CAD'),
                    CurrencyClass('EUR'),
                    CurrencyClass('AUD'),
                    CurrencyClass('SAD'),
                    CurrencyClass('KAD'),
                  ];
                  birrName = Text(
                    'Dim',
                    style: TextStyle(fontSize: 30.0),
                  );
                  convertText = Text(
                    'Jafida',
                    style: TextStyle(fontSize: 30.0, color: Colors.white),
                  );
                } else if (newValue == users[3]) {
                  currency = <CurrencyClass>[
                    CurrencyClass('TIG'),
                    CurrencyClass('GBP'),
                    CurrencyClass('CAD'),
                    CurrencyClass('EUR'),
                    CurrencyClass('AUD'),
                    CurrencyClass('SAD'),
                    CurrencyClass('KAD'),
                  ];
                  birrName = Text(
                    'Jaa',
                    style: TextStyle(fontSize: 30.0),
                  );
                  convertText = Text(
                    'Lewti',
                    style: TextStyle(fontSize: 30.0, color: Colors.white),
                  );
                } else {
                  currency = <CurrencyClass>[
                    CurrencyClass('SOM'),
                    CurrencyClass('GBP'),
                    CurrencyClass('CAD'),
                    CurrencyClass('EUR'),
                    CurrencyClass('AUD'),
                    CurrencyClass('SAD'),
                    CurrencyClass('KAD'),
                  ];
                  birrName = Text(
                    'Qoo',
                    style: TextStyle(fontSize: 30.0),
                  );
                  convertText = Text(
                    'Fola',
                    style: TextStyle(fontSize: 30.0, color: Colors.white),
                  );
                }
                selectedCurrency = currency[0];
              });
            },
            items: users.map((User user) {
              return DropdownMenuItem<User>(
                value: user,
                child: Text(
                  user.name,
                  style: TextStyle(color: Colors.black),
                ),
              );
            }).toList(),
           ),
         ],
       ),
        body: exchangeRate(),
      );
     }



     Widget exchangeRate() {
       return Container(
        child:Padding(
          padding: EdgeInsets.symmetric(vertical: 100.0,horizontal: 10.0),
           child: Column(
             children: <Widget>[
               Padding(
                padding: EdgeInsets.symmetric(horizontal: 100.0),
               child: Row(
                 children: <Widget>[
                   Container(
                    child: Expanded(
                      child: Center(
                        child: TextField(
                         decoration: InputDecoration.collapsed(
                         hintText: 'Enter..',
                         border: InputBorder.none,
                         ),
                      keyboardType: TextInputType.number,
                      style: TextStyle(fontSize: 30.0,color: Colors.black),
                      controller: myController,
                    ),
                  ),
                ),
                ),
                Padding(padding: EdgeInsets.symmetric(horizontal: 20.0),),
                // birrDefinition,
                DropdownButton<CurrencyClass>(
                    value: selectedCurrency,
                    onChanged: (CurrencyClass newExchange) {
                      setState(() {
                        selectedCurrency = newExchange;
                        selectedSymbol = selectedCurrency.toString();
                      });
                            },
                    items: currency.map((CurrencyClass currencyName) {
                      return DropdownMenuItem<CurrencyClass>(
                        value: currencyName,
                        child: Text(currencyName.currencyType,
                          style: TextStyle(color: Colors.red),),

                      );
                    }).toList()),
               ],
             ),
         ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 40.0),
            ),
            Expanded(
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 50.0),
                  ),
                  convertedAmount,//Converted Amount
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10.0),
                  ),
                  birrName
                ],
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0),
            ),
            Container(
              height: 50.0,
              width: 120.0,
              child: FlatButton(
                child: Center( child: convertText ),
                onPressed: () {
                  setState(() {
                    convertedAmount = Text("${int.parse(myController.text) * 
                        exchangeData}");
                  });
                },
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0)),
                color: Colors.black87,
               ),
             ),
            ],
          ),
         ),
       );
      }

       Future<double> fetchPost() async {


       final response = await 
       http.get('https://openexchangerates.org/api/latest.json? 
       app_id=ffffffffffffsssssss');

       if(response.statusCode == 200) {

            final responseJson = json.decode(response.body);
            exchangeData = responseJson["rates"][selectedSymbol];
            return exchangeData;

           }
       else {
          throw Exception('Failed to load post');
          }
        }
      }

2 个答案:

答案 0 :(得分:1)

您应该在onChanged内使用selectedCurrency而不是newExchange

onChanged: (CurrencyClass newExchange) {
    setState(() {
      selectedCurrency = newExchange;
      selectedSymbol = newExchange.currencyType;
    });
 }

答案 1 :(得分:0)

用@Dhiraj代码编辑代码后,它没有用,但有帮助。我从fetchPost()中删除了initState函数,并像这样将其添加到onChanged部分。

     @override
      void initState() {
      super.initState();
      selectedLanguage = users[0]; 
      // this.fetchPost();
       }

 DropdownButton<CurrencyClass>(
                value: selectedCurrency,
                onChanged: (CurrencyClass newExchange) {
                  setState(() {
                    selectedCurrency = newExchange;
                    selectedSymbol = newExchange.currencyType ;
                    fetchPost();
                  });

                        },
                items: currency.map((CurrencyClass currencyName) {
                  return DropdownMenuItem<CurrencyClass>(
                    value: currencyName,
                    child: Text(currencyName.currencyType,
                      style: TextStyle(color: Colors.red),),

                  );
                }).toList()),