Flutter Dart“期望一个标识符”和“期望找到')'”

lim*_*itt 4 rest json dart flutter

我正在尝试将对象与用户输入的字符串进行比较。该对象来自我映射的 json api 响应。我在“if”上收到错误:

                    MaterialButton(
                      child: Text("Connect"),
                      textColor: Colors.black,
                      onPressed: (){
                        fetchUser().then((user)=> (if user.username == username){
                          return Get.toNamed('/home');
                        });
                      },
                      color: Colors.grey[350],
                    )
Run Code Online (Sandbox Code Playgroud)

这是函数

Future <User>fetchUser() async{
var authresponse = await http.get(userCall);
if (authresponse.statusCode == 200){
var jsondata = jsonDecode(authresponse.body);
final data = apicallFromJson(jsondata);
var  user = data.subsonicResponse.user;
return user;
}else{
throw Exception("Unable to connect to server, try again");}
}
``

Run Code Online (Sandbox Code Playgroud)

Sri*_*tha 6

看起来这是一个简单的语法错误。我在这里更正了你的代码。

MaterialButton(
      child: Text("Connect"),
      textColor: Colors.black,
      onPressed: (){
         fetchUser().then((user){
            if(user.username == username){
                 return Get.toNamed('/home');
            }
         });
      },
      color: Colors.grey[350],
     )
Run Code Online (Sandbox Code Playgroud)

编辑1

深入研究这一点,当创建 .then() 时,它会像这样,

 onPressed: (){
    fetchUser().then((value) => null);
 },
Run Code Online (Sandbox Code Playgroud)

这是你犯错误的地方。=> 指向一个函数。所以当你在那里放置一个函数时,它应该只是函数的名称,如下所示,

onPressed: (){
     fetchUser().then((value) => myfunctions());
},
Run Code Online (Sandbox Code Playgroud)

但如果你在那里编写函数,它应该是这样的,

onPressed: (){
  fetchUser().then((value){
     //your code
  });
},
Run Code Online (Sandbox Code Playgroud)