【问题标题】:Flutter: 'Future<dynamic>' is not a subtype of type 'String'Flutter:“Future<dynamic>”不是“String”类型的子类型
【发布时间】:2020-12-09 00:35:08
【问题描述】:

我正在尝试使用以下 api 构建 URL 缩短器:https://shrtco.de/docs/。我解析了 JSON 文件并尝试重建列表视图。但是在添加 url 之后,我得到了上述错误。不过,当我打印它时,api 似乎工作正常。我不知道怎么了。我是 Flutter 和 Dart 的初学者。请帮帮我。

    class _homePageState extends State<homePage> {
  getdata(String userUrl) async {
    //JSON Parser
    var url = 'https://api.shrtco.de/v2/shorten?url=$userUrl';
    var respons = await http.get(url);
    var result = jsonDecode(respons.body);
    var shortlink = result['result']['short_link']; //dictionary parse
    print(shortlink);
    return shortlink;
  }

  Future<String> createAlertDialog(BuildContext context) {
    //method for alertdialog
    //promise to return string
    TextEditingController customController =
        TextEditingController(); //new texteditingc object
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("Enter URL: "),
            content: TextField(
              controller: customController,
            ),
            actions: [
              MaterialButton(
                elevation: 5.0,
                child: Text("OK"),
                onPressed: () {
                  if (customController.text != null &&
                      customController.text != "") {
                    var getShortlink = getdata(customController.text);
                    item.add(getShortlink);
                  }

                  setState(() {});
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    String temp;
    return Scaffold(
      appBar: AppBar(
        title: Text("Shortie"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: ListView.builder(
          itemCount: item.length,
          itemBuilder: (context, index) {
            return ListTile(
              leading: Icon(Icons.link),
              title: Text(item[index]),
              subtitle: Text("data"),
            );
            //return new Text();
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          createAlertDialog(context).then((onValue) {
            temp = onValue;
            print(temp);
          });
        },

【问题讨论】:

    标签: android json api flutter parsing


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    第 1 步:getdata 返回Future&lt;String&gt;
    第二步:onPressed需要asyncawait
    第 3 步:将 getShortlink 放入 Navigator.of(context).pop(getShortlink);
    代码sn-p

    Future<String> getdata(String userUrl) async {
    ...
    onPressed: () async {
          String getShortlink;
          if (customController.text != null &&
              customController.text != "") {
            getShortlink = await getdata(customController.text);
            item.add(getShortlink);
          }
    
          setState(() {});
          Navigator.of(context).pop(getShortlink);
        },
    

    工作演示

    完整代码

    import 'dart:convert';
    import 'package:http/http.dart' as http;
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      List<String> item = [];
    
      Future<String> getdata(String userUrl) async {
        //JSON Parser
        var url = 'https://api.shrtco.de/v2/shorten?url=$userUrl';
        var respons = await http.get(url);
        var result = jsonDecode(respons.body);
        var shortlink = result['result']['short_link']; //dictionary parse
        print(shortlink);
        return shortlink;
      }
    
      Future<String> createAlertDialog(BuildContext context) {
        //method for alertdialog
        //promise to return string
        TextEditingController customController =
            TextEditingController(text: "example.org/very/long/link.html"); //new texteditingc object
        return showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text("Enter URL: "),
                content: TextField(
                  controller: customController,
                ),
                actions: [
                  MaterialButton(
                    elevation: 5.0,
                    child: Text("OK"),
                    onPressed: () async {
                      String getShortlink;
                      if (customController.text != null &&
                          customController.text != "") {
                        getShortlink = await getdata(customController.text);
                        item.add(getShortlink);
                      }
    
                      setState(() {});
                      Navigator.of(context).pop(getShortlink);
                    },
                  )
                ],
              );
            });
      }
    
      @override
      Widget build(BuildContext context) {
        String temp;
        return Scaffold(
            appBar: AppBar(
              title: Text("Shortie"),
            ),
            body: Padding(
              padding: const EdgeInsets.all(8.0),
              child: ListView.builder(
                itemCount: item.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    leading: Icon(Icons.link),
                    title: Text(item[index]),
                    subtitle: Text("data"),
                  );
                  //return new Text();
                },
              ),
            ),
            floatingActionButton: FloatingActionButton(onPressed: () {
              createAlertDialog(context).then((onValue) {
                temp = onValue;
                print(temp);
              });
            }));
      }
    }
    

    【讨论】:

      【解决方案2】:

      createAlertDialog(BuildContext context) 不返回 Future&lt;String&gt;,而是返回 Future&lt;T&gt;,在您的情况下是动态的。 https://api.flutter.dev/flutter/material/showDialog.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 2019-08-04
        • 2018-09-28
        • 2019-12-05
        • 2019-08-18
        • 2023-03-30
        • 2021-09-18
        相关资源
        最近更新 更多