我是flutter的新手,如果我的问题是基本的,那很抱歉。类TelaDados
在类TelaPrecos
内部被调用,它有两个属性,其中一个是numeroSerie
。
在类_TelaDados
中,我可以使用widget.numeroSerie
获取属性numeroSerie
的值。
当我点击按钮Índice de preços
和IPCA - var. mensal
,有一个切换按钮。
我创建了一个名为numeroSerie
的顶级变量,我想用widget.numeroSerie
填充它。
只有当切换按钮切换到1(Sim
)时才需要使用numeroSerie
。
我可以填充numeroSerie
,因为我可以在屏幕和Android Studio控制台中的切换按钮上方打印它。但是当我尝试在称为getJsonFromRestAPI2
和onStart
的顶级函数中打印numeroSerie
的值时,它打印null
。
我需要在这个函数中使用这个变量,以便放置一个后台服务(我将使用API url中的数字),并测试是否有必要生成一个本地通知,以通知有一个来自API的新值。
我看了很多网站,我尝试了很多东西:FutureBuilder
,把变量放在initState
中。下面是我的代码(在onStart
函数中有一个print("onStart: $numeroSerie")
,它将变为null):
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart' hide TextDirection;
import 'package:toggle_switch/toggle_switch.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Permission.notification.isDenied.then(
(value){
if(value){
Permission.notification.request();
}
},
);
runApp(MaterialApp(
home: Home(),
debugShowCheckedModeBanner: false,
));
}
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Escolha o assunto"),
),
body: Container(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10),
child: Center(
child: ElevatedButton(
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(200, 40))
),
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TelaPrecos()
)
);
},
child: Text("Índices de preços")
),
),
)
],
),
),
);
}
}
class TelaPrecos extends StatefulWidget {
const TelaPrecos({super.key});
@override
State<TelaPrecos> createState() => _TelaPrecosState();
}
class _TelaPrecosState extends State<TelaPrecos> {
bool _isLoading = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Índices de preços"),
),
body: Container(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10),
child: Center(
child: ElevatedButton(
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(200, 40))
),
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TelaDados(numeroSerie: "433", nomeSerie: "IPCA - % mensal")
)
);
},
child: Text("IPCA - var. mensal")
),
),
),
],
),
),
);
}
}
class IPCA {
final DateTime data;
final double valor;
IPCA(this.data, this.valor);
factory IPCA.fromJson(Map<String, dynamic> parsedJson){
return IPCA(
DateFormat('MM/yyyy').parse(parsedJson['data'].substring(3)),
double.parse(parsedJson['valor']),
);
}
}
class TelaDados extends StatefulWidget {
//const TelaDados({super.key});
final String numeroSerie;
final String nomeSerie;
TelaDados({required this.numeroSerie, required this.nomeSerie});
@override
State<TelaDados> createState() => _TelaDados();
}
var numeroSerie;
var service;
Future<void> initializeService() async {
service = FlutterBackgroundService();
await service.configure(iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
onBackground: onIosBackground,
),
androidConfiguration: AndroidConfiguration(
onStart: onStart,
isForegroundMode: true,
autoStart: true
)
);
}
Future<String> getJsonFromRestAPI2() async {
String url = "https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados?formato=json";
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
@pragma('vm:registry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
return true;
}
List<IPCA> listaBack = [];
var ultimaDataIPCA;
Future loadIPCAData2() async {
String jsonString = await getJsonFromRestAPI2();
final jsonResponse = json.decode(jsonString);
for (Map<String, dynamic> i in jsonResponse){
listaBack.add(IPCA.fromJson(i));
}
ultimaDataIPCA = listaBack.last.data;
}
@pragma('vm:registry-point')
void onStart(ServiceInstance service) {
DartPluginRegistrant.ensureInitialized();
if(service is AndroidServiceInstance){
service.on("setAsForeground").listen((event) {
service.setAsForegroundService();
});
service.on("setAsBackground").listen((event) {
service.setAsBackgroundService();
});
}
service.on("stopService").listen((event) {
service.stopSelf();
});
Timer.periodic(const Duration(seconds: 1), (timer) async {
if(service is AndroidServiceInstance){
if(await service.isForegroundService()){
service.setForegroundNotificationInfo(title: "SCRIPT ACADEMY", content: "sub my channel");
}
}
// perfom some operation on background which is not noticeable to the user everytime
//print("background service running");
loadIPCAData2();
print("background service running $ultimaDataIPCA");
print("onStart: $numeroSerie");
});
}
class _TelaDados extends State<TelaDados> {
Future<String> getJsonFromRestAPI() async {
//String url = "https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados?formato=json";
String url = "https://api.bcb.gov.br/dados/serie/bcdata.sgs.${widget.numeroSerie}/dados?formato=json";
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
List<IPCA> chartData = [];
DateTime startval1 = DateFormat('MM/yyyy').parse('01/2021');
DateTime endval1 = DateFormat('MM/yyyy').parse('12/2021');
TextEditingController dateInputEnd = TextEditingController();
TextEditingController dateInputIni = TextEditingController();
Future loadIPCAData() async {
String jsonString = await getJsonFromRestAPI();
final jsonResponse = json.decode(jsonString);
setState(() {
for (Map<String, dynamic> i in jsonResponse){
chartData.add(IPCA.fromJson(i));
}
endval1 = chartData.last.data;
startval1 = chartData[chartData.length-13].data;
});
}
List<IPCA> itemsBetweenDates({
required List<IPCA> lista,
required DateTime start,
required DateTime end,
}) {
var output = <IPCA>[];
for (var i = 0; i < lista.length; i += 1) {
DateTime date = lista[i].data;
if (date.compareTo(start) >= 0 && date.compareTo(end) <= 0) {
output.add(lista[i]);
}
}
return output;
}
@override
void initState() {
// TODO: implement initState
super.initState();
loadIPCAData();
numeroSerie = widget.numeroSerie;
}
var initialIndex = 0;
@override
Widget build(BuildContext context) {
filtrarDados(){
dateInputIni.text = DateFormat('MM/yyyy').format(startval1).toString();
dateInputEnd.text = DateFormat('MM/yyyy').format(endval1).toString();
DateTime dataIni = DateFormat('MM/yyyy').parse(dateInputIni.text.toString());
DateTime dataFim = DateFormat('MM/yyyy').parse(dateInputEnd.text.toString());
late var lista_filtrada = itemsBetweenDates(lista: chartData, start: dataIni, end: dataFim);
lista_filtrada.sort((a, b){ //sorting in descending order
return a.data.compareTo(b.data);
});
return lista_filtrada;
}
return Scaffold(
appBar: AppBar(
title: Text("${widget.nomeSerie}"),
),
body: SingleChildScrollView(
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.all(40),
child: Column(
children: <Widget>[
ToggleSwitch(
initialLabelIndex: initialIndex,
totalSwitches: 2,
labels: [
'Não',
'Sim',
],
onToggle: (index) async {
final service = FlutterBackgroundService();
if(index==1){
await initializeService();
service.startService();
} else {
service.invoke("stopService");
}
setState(() {
initialIndex = index!;
});
},
),
],
)
)
]
)
)
);
}
}
字符串
欢迎提出任何建议!打扰了。
1条答案
按热度按时间o4tp2gmn1#
我解决了我的问题:
a)我使用了
shared_preferences
库,并将此代码放入getJsonFromRestAPI
函数中,以在本地保存numeroSerie
:字符串
B)我创建了这个函数来读取保存的数据:
型
c)在
onStart
函数中,我将以下代码用于读取变量numeroSGS
的数据和属性型