Flutter:“Future<dynamic>”不是“String”类型的子类型

Posted

技术标签:

【中文标题】Flutter:“Future<dynamic>”不是“String”类型的子类型【英文标题】:Flutter: 'Future<dynamic>' is not a subtype of type '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);
          );
        ,

【问题讨论】:

【参考方案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

【讨论】:

以上是关于Flutter:“Future<dynamic>”不是“String”类型的子类型的主要内容,如果未能解决你的问题,请参考以下文章

Flutter 致命错误:找不到“Flutter/Flutter.h”文件

[Flutter] flutter项目一直卡在 Running Gradle task 'assembleDebug'...

flutter 日志输出,Flutter打印日志,flutter log,flutter 真机日志

Flutter开发 Flutter 包和插件 ( Flutter 包和插件简介 | 创建 Flutter 插件 | 创建 Dart 包 )

flutter与原生混编(iOS)

Flutter-布局