如何在 Flutter 中运行函数并获取值并将其添加到文本中
Posted
技术标签:
【中文标题】如何在 Flutter 中运行函数并获取值并将其添加到文本中【英文标题】:How to run a function and get a value and add it in text in Flutter 【发布时间】:2020-10-17 20:58:03 【问题描述】:各位,我在 Flutter 中写了如下代码
import 'dart:ui';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(Myapp());
class Myapp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Hello World'),
centerTitle: true,
backgroundColor: Colors.blueAccent,
),
body: Center(child: MyStatefulWidget(),
),
)
);
class Weather extends StatefulWidget
UpdateTextState createState() => UpdateTextState();
class UpdateTextState extends State
// var textHolder = 'Getting';
weath() async
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.latitude);
print(position.longitude);
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=$position.latitude&lon=$position.longitude&appid=myapiid';
print(url);
var response = await http.get(url);
var dart = json.decode(response.body);
var dartt = dart['main'];
var climate = dartt['temp'];
var weather = climate - 32 * 5/9;
// print('Response status: $response.statusCode');
// print('Response body: $json.decode(response.body)');
// print(dart['main']);
// print(dartt['temp']);
var textHolder = '$weather.toString()C';
return textHolder;
@override
Widget build(BuildContext context)
var c = weath();
//print(textHolder);
//changeText();
return Scaffold(
body: Center(child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
child: Text(c),
),
]))
);
如果我运行这个程序,这是我得到的输出 Please refer to This image 实际上我想要从 API 获得的天气,它是文本保持器变量,请帮助我,我什至尝试过没有返回语句,我也尝试过直接添加也没有很好的功能基本上是有任何替代方法还是我在代码中犯了任何错误
【问题讨论】:
【参考方案1】:这是一个 Future,因此您可以在 initState 中调用它并使用 setState 更新 c
变量。或者你可以使用 FutureBuilder。
class Weather extends StatefulWidget
UpdateTextState createState() => UpdateTextState();
class UpdateTextState extends State
var c = 'Getting';
weath() async
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.latitude);
print(position.longitude);
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=$position.latitude&lon=$position.longitude&appid=myapiid';
print(url);
var response = await http.get(url);
var dart = json.decode(response.body);
var dartt = dart['main'];
var climate = dartt['temp'];
var weather = climate - 32 * 5/9;
// print('Response status: $response.statusCode');
// print('Response body: $json.decode(response.body)');
// print(dart['main']);
// print(dartt['temp']);
var textHolder = '$weather.toString()C';
setState(()
c = textHolder;
);
@override
void initState()
super.initState();
weath();
@override
Widget build(BuildContext context)
var c = weath();
//print(textHolder);
//changeText();
return Scaffold(
body: Center(child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
child: Text(c),
),
]))
);
【讨论】:
【参考方案2】:只需使用 setState(())。不要使用 return weath(),因为 async 是后台线程,而 textView 需要 UI。
var c = "";
@override
void initState()
super.initState();
weath()
weath() async
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=$position.latitude&lon=$position.longitude&appid=myapiid';
print(url);
var response = await http.get(url);
var dart = json.decode(response.body);
var dartt = dart['main'];
var climate = dartt['temp'];
var weather = climate - 32 * 5/9;
setState(()
c = '$weatherC'; );
【讨论】:
您好,谢谢您的回复,我尝试了这段代码 vs 代码告诉我这样 paste.pics/cd24e7ad8beb0c83a245a73e6bd100d3 并且在我的 UI 上它是空白的 setState(() c = '$weatherC'; );另见编辑后的答案【参考方案3】:添加 Future 作为返回类型,因为您在异步函数中返回值
Future<String> weath() async
像这样修改Build方法
Widget build(BuildContext context)
return FutureBuilder(
future: weath(),
builder: (ctx, snapshot)
return Scaffold(
body: Center(
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
child: Text(snapshot.data.toString()),
),
])));
);
【讨论】:
感谢您的回复,但效果不佳 你得到了什么 var textHolder = '$weather.toString()C';添加打印声明并告诉我 如果我在函数内打印,我得到正确的天气 278.15222222222224C以上是关于如何在 Flutter 中运行函数并获取值并将其添加到文本中的主要内容,如果未能解决你的问题,请参考以下文章
如何创建一个 Flutter Futurebuilder 函数来显示从 JSON 中获取的字符串数组?
Flutter:如何在运行 JavaScript 函数并显示 html 后等待 WebView 完成加载?