【问题标题】:Get Json data function works in Stateless Widget in the Main class but not in the Stateful Widget in a different class获取 Json 数据功能在 Main 类的 Stateless Widget 中有效,但在不同类的 Stateful Widget 中无效
【发布时间】:2021-06-24 01:16:58
【问题描述】:

您好,我尝试在 initState 和 WidgetBuild 方法中调用 getContacts() 函数,但我没有得到任何响应,而当我尝试在无状态小部件主类中使用相同的函数并在 WidgetBuild 方法中调用它时,它可以工作.

class ContactsPage extends StatefulWidget {
  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage>
    with SingleTickerProviderStateMixin {
  Query _ref;
  bool isSearching = false;

  get reference => null;
  TabController _tabController;

  Future<void> getContacts() async {
    var client = http.Client();
    String contacts_url =
        'api url example';
    String basicAuth = 'Basic auth example';
    var response = await client.get(contacts_url,
        headers: <String, String>{'authorization': basicAuth});
    print(response.statusCode);
    developer.log(response.body);
  }

@override
  Widget build(BuildContext context) {
    getContacts();
    return DefaultTabController(
        length: 2,
..........
.......

【问题讨论】:

    标签: json api flutter dart rest


    【解决方案1】:

    我真的不明白你的意图是什么。如果您想在构建方法中使用 getContacts 返回的值,可以选择使用 FutureBuilder。这将允许您根据 Future 的状态轻松实现控制流。在下面找到代码,我为示例模拟了 getContacts 方法的行为。

    class ContactsPage extends StatefulWidget {
      @override
      _ContactsPageState createState() => _ContactsPageState();
    }
    
    class _ContactsPageState extends State<ContactsPage> {
      Future<List<String>> getContacts() {
        return Future.value(['Contact A', 'Contact B', 'Contact C']);
      }
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
          future: getContacts(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              final contacts = snapshot.data as List<String>;
    
              return ListView.builder(
                itemCount: contacts.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(title: Text(contacts[index]));
                },
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        );
      }
    }
    

    【讨论】:

    • 这是对的,但我的问题是当我调用 getContacts() 方法时,我没有从 API(状态代码:200)获得响应。但是当我在 Main 类 StatelessWidget 中使用相同的方法时,我得到了响应。
    • 您是否分析了网络活动以找出问题所在?
    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2021-06-08
    • 2019-07-08
    • 2020-02-27
    • 2021-04-28
    • 2020-08-02
    • 2021-05-26
    相关资源
    最近更新 更多