有时会变化,有时它不是

发布于 2025-02-03 18:00:45 字数 1949 浏览 2 评论 0原文

首先,很抱歉标题中缺乏信息,我只是想不到任何更好的写作。

我的问题是我正在从在线API中解析JSON数据,有时它会显示我想要显示的内容,有时它不是...这是代码:(

第一个代码块是我的类别。 '将在第二块中使用,这是重要的部分,可能是我认为问题所在的地方)

import 'dart:convert';
import 'package:http/http.dart' as http;

class CanteenInfo {
  final String canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
  List canteenMenu = [];
  var data;
  String workingHours = "yes";

  CanteenInfo() {
    getWebsiteData();
  }

  Future getWebsiteData() async {
    var response =  await http.get(Uri.parse(canteenUrl));
    if (response.statusCode == 200) {
      data = json.decode(response.body);
      workingHours = data[3]["horario"];
      print("Hours: " + workingHours);
    }
    else {
      throw Exception('Failed to read $canteenUrl');
    }
  }
}
class WorkingHours extends StatefulWidget {
  const WorkingHours({Key? key}) : super(key: key);

  @override
  State<WorkingHours> createState() => _WorkingHours();
}

class _WorkingHours extends State<WorkingHours> {

  String hours = "yes";
  CanteenInfo canteen = CanteenInfo();

  void getHours() {
    setState(() {
      hours = canteen.getHours();
    });
  }

  @override
  Widget build(BuildContext context) {

    getHours();

    return Scaffold(
      appBar: AppBar(
        title: Text('EasyFood'),
      ),
      body: Center(
        child: Container (
          margin: const EdgeInsets.only(top: 100),
          child: Column(
            children: <Widget>[
              Text(
                  'Lunch: ' + hours,
                  style: const TextStyle(
                      fontSize: 20
                  )
              ),
            ],
          ),
        ),
      ),
    );
  }
}

如果我没有明确问题,那么当我运行代码时,有时会将文本显示为“午餐:是的:“有时是正确的事情,即“午餐:11:30 - 14:00”。

通过我的理解,我认为发生了什么事,有时代码可以获取API信息和时间,并且有时间在页面加载之前更改变量,有时没有。无论哪种方式,我都不知道如何修复它,因此,如果有人有任何想法,我会不愿意为帮助:)

感谢您抽出宝贵的时间阅读此书

first of all, sorry for the lack of information in the title, I just couldn't think of anything better to write.

My problem is that I'm parsing JSON data from an online API and sometimes it displays what I want it to display, and sometimes it doesn't... here is the code:

(The first code block is the class of what I'll be using in the second block, which is the important part and probably where I think the problem is coming from)

import 'dart:convert';
import 'package:http/http.dart' as http;

class CanteenInfo {
  final String canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
  List canteenMenu = [];
  var data;
  String workingHours = "yes";

  CanteenInfo() {
    getWebsiteData();
  }

  Future getWebsiteData() async {
    var response =  await http.get(Uri.parse(canteenUrl));
    if (response.statusCode == 200) {
      data = json.decode(response.body);
      workingHours = data[3]["horario"];
      print("Hours: " + workingHours);
    }
    else {
      throw Exception('Failed to read $canteenUrl');
    }
  }
}
class WorkingHours extends StatefulWidget {
  const WorkingHours({Key? key}) : super(key: key);

  @override
  State<WorkingHours> createState() => _WorkingHours();
}

class _WorkingHours extends State<WorkingHours> {

  String hours = "yes";
  CanteenInfo canteen = CanteenInfo();

  void getHours() {
    setState(() {
      hours = canteen.getHours();
    });
  }

  @override
  Widget build(BuildContext context) {

    getHours();

    return Scaffold(
      appBar: AppBar(
        title: Text('EasyFood'),
      ),
      body: Center(
        child: Container (
          margin: const EdgeInsets.only(top: 100),
          child: Column(
            children: <Widget>[
              Text(
                  'Lunch: ' + hours,
                  style: const TextStyle(
                      fontSize: 20
                  )
              ),
            ],
          ),
        ),
      ),
    );
  }
}

If I haven't made my problem clear, when I run the code, sometimes it displays the text as "Lunch: yes" and sometimes as the correct thing, which is "Lunch: 11:30 às 14:00".

By my understanding, I think what's happening is that sometimes the code can get the API information and time and has time to change the variable before the page loads, and sometimes it doesn't. Either way, I don't know how to fix it so if anyone has any idea I would relly appreciate the help :)

Thanks alot for taking the time to read this

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黎夕旧梦 2025-02-10 18:00:45

我不确定在CanteenInfo中是否存在Gethours方法。
但是,您可能需要在您的已成状态小部件中覆盖initstate方法并致电

canteen.getWebsiteData().then((value) {
  setState(() => hours = canteen.workingHours);
});

或类似的东西,具体取决于哪种方法返回API的数据

I'm not sure if getHours method exists in CanteenInfo.
But you probably need to override initState method in your stateful widget and call

canteen.getWebsiteData().then((value) {
  setState(() => hours = canteen.workingHours);
});

or something like that depending on which method returns data from API

你穿错了嫁妆 2025-02-10 18:00:45

一个很好的决定是等待食堂对象“食堂”

var flag = false;
loadData()async{
    flag = true;
    canteen = CanteenInfo();
    await getHours();
    setState((){flag=false;});
}
Widget build(BuildContext context) {

    if (hours == "yes" && !flag)
      loadData();
    if (flag)
      return Scaffold(body:CircularProgressIndicator());
    return Scaffold(
      appBar: AppBar(
        title: Text('EasyFood'),
      ),
      body: Center(
        child: Container (
          margin: const EdgeInsets.only(top: 100),
          child: Column(
            children: <Widget>[
              Text(
                  'Lunch: ' + hours,
                  style: const TextStyle(
                      fontSize: 20
                  )
              ),
            ],
          ),
        ),
      ),
    );
}

A good decision will be to wait CanteenInfo object "canteen" to be initialized, smth like this:

var flag = false;
loadData()async{
    flag = true;
    canteen = CanteenInfo();
    await getHours();
    setState((){flag=false;});
}
Widget build(BuildContext context) {

    if (hours == "yes" && !flag)
      loadData();
    if (flag)
      return Scaffold(body:CircularProgressIndicator());
    return Scaffold(
      appBar: AppBar(
        title: Text('EasyFood'),
      ),
      body: Center(
        child: Container (
          margin: const EdgeInsets.only(top: 100),
          child: Column(
            children: <Widget>[
              Text(
                  'Lunch: ' + hours,
                  style: const TextStyle(
                      fontSize: 20
                  )
              ),
            ],
          ),
        ),
      ),
    );
}

I'm not sure if class object initialization works correct here, maybe you also need to add async/await

歌入人心 2025-02-10 18:00:45
class CanteenInfo {
  final String canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
  List canteenMenu = [];
  var data;
  String workingHours = "yes";
  
  getWebsiteData() async {
    var response =  await http.get(Uri.parse(canteenUrl));
    if (response.statusCode == 200) {
      data = json.decode(response.body);
      workingHours = data[3]["horario"];
      print("Hours: " + workingHours);
    }
    else {
      throw Exception('Failed to read $canteenUrl');
    }
  }
  
  getHours() {
    return workingHours;
  }
}

// ------------------------

class WorkingHours extends StatefulWidget {
  const WorkingHours({Key? key}) : super(key: key);

  @override
  State<WorkingHours> createState() => _WorkingHours();
}

// ------------------------

class _WorkingHours extends State<WorkingHours> {

  String hours = "yes";
  CanteenInfo canteen = CanteenInfo();
  
  @override
  void initState() {
    super.initState();
    canteen.getWebsiteData().then(() {
      hours = canteen.getHours();
    });
  }
}
class CanteenInfo {
  final String canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
  List canteenMenu = [];
  var data;
  String workingHours = "yes";
  
  getWebsiteData() async {
    var response =  await http.get(Uri.parse(canteenUrl));
    if (response.statusCode == 200) {
      data = json.decode(response.body);
      workingHours = data[3]["horario"];
      print("Hours: " + workingHours);
    }
    else {
      throw Exception('Failed to read $canteenUrl');
    }
  }
  
  getHours() {
    return workingHours;
  }
}

// ------------------------

class WorkingHours extends StatefulWidget {
  const WorkingHours({Key? key}) : super(key: key);

  @override
  State<WorkingHours> createState() => _WorkingHours();
}

// ------------------------

class _WorkingHours extends State<WorkingHours> {

  String hours = "yes";
  CanteenInfo canteen = CanteenInfo();
  
  @override
  void initState() {
    super.initState();
    canteen.getWebsiteData().then(() {
      hours = canteen.getHours();
    });
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文