Flutter:如何在子窗口小部件的构建上下文之外的函数中访问'provider'值?

问题描述 投票:0回答:1

提供者值来自父窗口小部件。我可以在构建上下文下使用提供程序值。但是,我需要getHomeCampaigns函数中的提供程序值。构建小部件后,我尝试定义局部变量并将其分配给提供程序值,但是该函数声称在null上调用了这些变量。我猜想它们是在使用之前在提供程序的构建上下文中进行设置的。

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  // Variables to be set inside the function and then used by the last widget
  User currentUser;
  String country;
  List<CampaignWidget> friendsCamps;
  List<CampaignWidget> featuredCamps;

  // Function that needs the provider values
  getHomeCampaigns() async {
    // Get all campaigns where their owner is in the list of friends for the current user
    QuerySnapshot friendsSnapshot = await Firestore.instance
        .collection('campaigns')
        .where('user.uid', whereIn: currentUser.friends)
        .where('attributes.active', isEqualTo: true)
        .orderBy('created', descending: true)
        .limit(20)
        .getDocuments();
    // Get featured campaigns documents in the current country
    QuerySnapshot featuredSnapshot = await Firestore.instance
        .collection('campaigns')
        .where('attributes.featured', isEqualTo: true)
        .where('funders.${currentUser.uid}', isEqualTo: false)
        .where('country', isEqualTo: country)
        .orderBy('user.rating', descending: true)
        .limit(5)
        .getDocuments();
    // Make 2 lists of CampaignWidget out of the documents retrieved
    List<CampaignWidget> campaigns = friendsSnapshot.documents
        .map((doc) => CampaignWidget(campaign: Campaign.fromDocument(doc)))
        .toList();
    List<CampaignWidget> featured = featuredSnapshot.documents
        .map((doc) => CampaignWidget(campaign: Campaign.fromDocument(doc)))
        .toList();
    setState(() {
      // Set the featured and friends lists of CampaignWidget to the newly made lists
      this.featuredCamps = featured;
      this.friendsCamps = campaigns;
    });
  }

  @override
  void initState() {
    super.initState();
    getHomeCampaigns();
  }

  @override
  Widget build(BuildContext context) {
    this.currentUser = Provider.of<User>(context);
    this.country = Provider.of<String>(context);
    return Scaffold(
      backgroundColor: Color(0xFFE8E8E8),
      appBar: AppBar(
        centerTitle: false,
        title: Text("Home"),
        actions: <Widget>[
          /// Search users
          IconButton(
            icon: Icon(
              Icons.search,
            ),
            onPressed: () {},
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () => getHomeCampaigns(),
        child: // Some widget that uses the variables,
      ),
    );
  }
}
flutter dart provider
1个回答
0
投票

根据您显示的代码,我想这是您设置提供程序的方式存在问题。但是,如果您正确设置了提供程序,则可以像下面这样从提供程序中读取变量:Provider.of(context, listen: false).yourVariable中的getHomeCampaigns。您必须具有listen: false才能起作用。

© www.soinside.com 2019 - 2024. All rights reserved.