【问题标题】:Flutter api data not showing in a widgetFlutter api数据未显示在小部件中
【发布时间】:2021-01-25 15:40:21
【问题描述】:

我有一个从 api 获取数据的简单页面。问题是数据已成功获取但未显示在小部件中。它有时会显示,但大多数时候不会显示。我想要的是当用户访问或返回此页面时,api 将点击并在小部件中显示数据。

class AddressPage extends StatefulWidget {
  @override
  _AddressPageState createState() => _AddressPageState();
}

class _AddressPageState extends State<AddressPage> {
  var address = {'Address': []};
  bool showAddress = false;
  int dateindex = 0;
  var addressSelected;

  @override
  void initState() {
    setState(() {
      getAddress();
    });
  }

  getAddress() async {
    final storage = new FlutterSecureStorage();

    String _userEmail = await storage.read(key: "_userEmail");
    String _userPassword = await storage.read(key: "_userPassword");
    String url =
        'http://retailapi.airtechsolutions.pk/api/customer/login/${_userEmail}/${_userPassword}';

    print(url);
    http.Response res = await http.get(
      url,
    );
    var data = json.decode(res.body.toString());
    print(data);

    if (data['description'].toString() == "Success") {
      print(data['customer']['Addresses']);
      address['Address'].addAll(data['customer']['Addresses']);

      print(address);

      setState(() {

        showAddress == true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            showAddress
                ? Flexible(
                    flex: 9,
                    child: SingleChildScrollView(
                      padding: EdgeInsets.symmetric(horizontal: 18.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 20.0),
                          Text(
                            'order.shippingaddress',
                            style: Theme.of(context).textTheme.headline4,
                          ).tr(),
                          SizedBox(height: 20.0),
                          ListView.builder(
                            itemCount: address['Address'].length,
                            shrinkWrap: true,
                            scrollDirection: Axis.vertical,
                            physics: ScrollPhysics(),
                            itemBuilder: (context, index) {
                              return SideInAnimation(
                                index,
                                child: GestureDetector(
                                  // onTap: widget.onPressed,
                                  onTap: () {
                                    setState(() {
                                      dateindex = index;
                                      addressSelected =
                                          address['Address'][index];
                                      print(addressSelected);
                                    });
                                  },
                                  child: Container(
                                    width: double.infinity,
                                    padding: EdgeInsets.all(15.0),
                                    margin: EdgeInsets.only(bottom: 15.0),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(12.0),
                                      border: Border.all(
                                        color: dateindex == index
                                            ? Theme.of(context).primaryColor
                                            : Theme.of(context).accentColor,
                                        width: dateindex == index ? 2.0 : 1.0,
                                      ),
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                            showAddress
                                                ? address['Address'][index]
                                                    ['Address']
                                                : '...',
                                            style: Theme.of(context)
                                                .textTheme
                                                .headline4),
                                        SizedBox(height: 8.0),
                                        Text(
                                            showAddress
                                                ? address['Address'][index]
                                                    ['Address']
                                                : '...',
                                            style: Theme.of(context)
                                                .textTheme
                                                .subtitle1),
                                        SizedBox(height: 8.0),
                                        Text(
                                            showAddress
                                                ? address['Address'][index]
                                                    ['Address']
                                                : '...',
                                            style: Theme.of(context)
                                                .textTheme
                                                .subtitle1),
                                        SizedBox(height: 8.0),
                                        Row(
                                          children: [
                                            SizedBox(
                                              width: 80.0,
                                              child: RaisedButtonWidget(
                                                title: 'product.edit',
                                                onPressed: () {
                                                  Get.to(AddAddressPage());
                                                },
                                              ),
                                            ),
                                            SizedBox(width: 15.0),
                                            IconButton(
                                              icon: Icon(Icons.delete_outline),
                                              onPressed: () {
                                                // showDeleteConfirmation(context);
                                              },
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                          SizedBox(height: 25.0),
                        ],
                      ),
                    ),
                  )
                : Container(),
            buildConfirmAddressButton(),
          ],
        ),
      ),
    );
  }

  Flexible buildConfirmAddressButton() {
    return Flexible(
      flex: 1,
      child: Padding(
        padding: EdgeInsets.fromLTRB(18.0, 0.0, 18.0, 15.0),
        child: FadeInAnimation(
          2,
          child: RaisedButtonWidget(
            title: 'order.next',
            onPressed: navigateToPaymentPage,
          ),
        ),
      ),
    );
  }

  void navigateToPaymentPage() {
    Get.to(PaymentPage());
  }

  AppBar buildAppBar(BuildContext context) {
    return AppBar(
      centerTitle: true,
      title: Text(
        'order.checkout',
        style: Theme.of(context).textTheme.headline4,
      ).tr(),
      actions: [
        IconButton(
          icon: Icon(Icons.add),
          color: Theme.of(context).primaryColor,
          onPressed: () {
            Get.to(AddAddressPage());
          },
        ),
      ],
    );
  }
}

不明白为什么它没有显示在小部件中以及为什么有时它会显示:D 我很困惑

【问题讨论】:

  • 您是否尝试过使用callBack,正如您所说,当用户返回此页面时,API 必须命中?

标签: flutter dart


【解决方案1】:

你写的:

setState(() {
  showAddress == true;
});

而不是

setState(() {
  showAddress = true;
});

双等号用于检查 2 个值。
简单相等用于赋值。

:)

【讨论】:

  • 是的:D 你能告诉我当我从其他页面访问页面时如何调用 api 函数(getAddress())吗?
  • 嗯,也许与 didDependenciesUpdate / DidWidgetUpdate 类似。但是,我需要更多上下文:我认为您的第一页进行了 api 调用,您向他推送了一些路由,当离开这些路由时,您会看到更新的数据吗?
  • 你也许可以用这篇文章来听导航器,我认为:stackoverflow.com/questions/55632161/…它可能会回应你的问题。
猜你喜欢
  • 2021-02-10
  • 2020-09-09
  • 1970-01-01
  • 2021-11-28
  • 2020-06-26
  • 2021-10-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多