提问者:小点点

错误:预期值为'Uri'类型,但得到了'String'类型[重复]


Flutter应用程序:

当我按下按钮时,我希望得到新的字符串,但得到我的问题标题的错误,我知道我这是一个“类型”错误,但不确定我在哪里给出那个“字符串”值,那么如何修复我的代码呢?任何帮助都不胜感激!

如果有帮助,完全错误:https://textuploader.com/tdhk0

这是我的flutter代码(request. dart和main.dar):

//request dart-------------------------

import 'package:http/http.dart';

Future getData(url) async {
  Response response = await get(url);
  return response.body;
}
//main.dart-------------------------------

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:passg/request.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
                title: Text('Change Text Dynamically on Button Click')
            ),
            body: Center(
                child: UpdateText()
            )
        )
    );
  }
}

class UpdateText extends StatefulWidget {

  UpdateTextState createState() => UpdateTextState();

}

class UpdateTextState extends State {

  String textHolder = 'Old Sample Text...!!!';

  changeText() async {
    var data = await getData('http://10.0.2.2:5000/passg');
    var decodedData = jsonDecode(data);
    setState(() {
      textHolder = decodedData;
    });

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(child: Column(
            children: <Widget>[
              Container(
                  padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                  child: Text('$textHolder',
                      style: TextStyle(fontSize: 21))),

              ElevatedButton(
                onPressed: () => changeText(),
                child: Text('Click Here To Change Text Widget Text Dynamically'),
              ),

            ]))
    );
  }
}```


共2个答案

匿名用户

尝试以这种方式创建您的url:

var data = await getData(Uri.parse('http://10.0.2.2:5000/passg'));

匿名用户

问题的根源在于参数缺少类型。这样一来,参数就变成了动态,这使得Dart分析器无法在运行应用程序之前识别潜在的类型问题。因此,当涉及方法和类字段的签名时,您应该始终明确指定类型。

问题是这个方法:

Future getData(url) async {
  Response response = await get(url);
  return response.body;
}

如果您想这样做,url参数应该是Uri类型。或者,您可以将其设为String,但您需要将该String解析为Uri,如下所示:

Future getData(String url) async {
  Response response = await get(Uri.parse(url));
  return response.body;
}

您可以从超文本传输协议包中读取get()方法的留档,以查看它期望的Uri:https://pub.dev/documentation/http/latest/http/Client/get.html