gpt4 book ai didi

flutter - 如何将信息从小部件功能返回到另一个页面?

转载 作者:行者123 更新时间:2023-12-03 03:58:41 25 4
gpt4 key购买 nike

我目前正在与一个团队合作一个项目,在该项目中我实现了一个条形码扫描仪,它将成为“搜索”页面上的一个小部件。我目前面临的问题是我使用条形码生成要包含在搜索中的成分列表,但我不知道如何将该信息返回到搜索页面。到目前为止,我已经尝试了两种方法:

  • 我尝试创建扫描程序类的成员变量,然后在需要时在搜索页面上访问它,但是因为返回列表的函数是私有(private)状态类的一部分,我不确定如何从公共(public)类访问.这是我希望解决的方法。
  • 我尝试使用 Navigator 类从单独的屏幕推送和弹出信息,但问题是条形码扫描仪在扫描条形码后自动关闭,因此我无法从堆栈中弹出,否则它将离开搜索页面和返回上一页。

  • 这是我的代码。第一个是打开条形码扫描仪、扫描条形码并创建我返回的成分列表的功能。这个“测试”列表是我理想的设置为类的公共(public)部分而不是私有(private)状态类的类成员。
    Future<void> scanBarcodeNormal(BuildContext context) async {
    String barcodeScanRes;
    List<String> test;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
    barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
    "#ff6666", "Cancel", true, ScanMode.BARCODE);
    } on PlatformException {
    barcodeScanRes = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return null;

    //Call the backend with the barcode to return the Bread Crumb list
    List<String> breadCrumbs = await BackendRequest.barcode("089836187635", "42e96d88b6684215c9e260273b5e56b0522de18e");

    //If the backend does not return us anything this displays a popup
    if(breadCrumbs == null){
    showDialog(
    context: context,
    builder: (BuildContext context) => CustomDialog(
    title: "Uh Oh",
    description:
    "Barcode not found in our database, please try entering the item manually",
    buttonText: "Okay",
    ),
    );
    }
    else{
    setState(() {
    _scanBarcode = breadCrumbs.toString();
    });

    //Check the breadcrumbs for usable ingredients
    test = await getIngredients(breadCrumbs, "42e96d88b6684215c9e260273b5e56b0522de18e");
    }

    setState(() {
    _itemName = test[0].toString();
    });

    //Navigator.pop(context, test);

    }

    这是我将小部件添加到搜索页面的地方。我所做的只是在我的扫描仪类中添加小部件和构建函数来处理 onPressed() 功能。
    decoration: InputDecoration(
    labelText: "Input an Ingredient",
    hintText: "Search",
    prefixIcon: Icon(Icons.search),
    suffixIcon: ScanButton(),

    最佳答案

    您可以使用提供消费者模式,在该模式中,您可以将所有页面放入一个父主题子主题中,然后您可以访问变量和所有其他内容。

    https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple



    否则你也可以使用 block 模式

    https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1



    或者如果您不想在这种情况下使用它,您可以创建一个公共(public)类并在其中声明一个静态变量,并在扫描完成后在结果上设置变量,并在您需要时使用

    关于flutter - 如何将信息从小部件功能返回到另一个页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922429/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com