【问题标题】:Flutter: Instances Data get Lost with Provider when I pass to another screenFlutter:当我传递到另一个屏幕时,实例数据与 Provider 一起丢失
【发布时间】:2021-12-11 12:51:10
【问题描述】:

我正在尝试将我的所有列表实例从我的列表提供程序类传递到我的 home_creen,但数据在此过程中丢失了。我该如何解决这个问题?

这是我的 ListingProvider 类,我用它来调用我的 MongoDB 数据库。


class ListingProvider extends ChangeNotifier {
  var url = Uri.parse('${Constants.apiUrl}listings/');

  List<Listing> onDisplayListing = [];

  ListingProvider() {
    print("Listing Provider inicializado");
    //this.getListing();
  }

  getListing(Token token) async {
    var response = await http.get(
      url,
      headers: {
        'content-type': 'application/json',
        'accept': 'application/json',
        'authorization': "Bearer ${token.token}"
      },
    );

    final nowListingResponse = ListingResponse.fromJson(response.body);

    onDisplayListing = nowListingResponse.results;

    notifyListeners();
  }
}

在使用 vscode 调试器时,我注意到我的:

onDisplayListing = nowListingResponse.results

像这样保存我的数据库数据的实例:

  • [0] 列表 [1] 列表 [2] 列表 [3] 列表

到目前为止一切顺利。当我尝试在我的主屏幕中使用这些实例时,我的:

listingProvider.onDisplayListing

没有这些实例。

我的主屏幕

class HomePage extends StatefulWidget {
  final Token token;
  const HomePage({required this.token, Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  initState() {
    super.initState();
    ListingProvider().getListing(widget.token);
  }

  @override
  Widget build(BuildContext context) {
    
    final listingProvider = Provider.of<ListingProvider>(
      context,
    );


//when I try to print here my instances, they are empty. Why?
    print(listingProvider.onDisplayListing);


    return Scaffold(
      appBar: AppBar(
        title: const Text("Find Shipments"),
      ),
      body: Center(
        child: Text("Hola ${widget.token.user.name}!"),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            MyHeaderDrawer(
              token: widget.token,
            ),
            myDrawerListOption(),
          ],
        ),
      ),
    );
  }

如果您还需要了解其他信息,请告诉我。

谢谢!!!

【问题讨论】:

  • 可能你的数据输出有误。读这个。 Read this example 你需要使用 Consumer

标签: flutter flutter-provider


【解决方案1】:

在你的

@override
initState() {
    super.initState();
    ListingProvider().getListing(widget.token);
 }

您创建一个新的 Provider 实例,而在您的 build() 函数中,您正在使用 Provider.of() 检索该提供程序。所以事实上你正在使用不同的提供者实例。

其次,您需要在提供程序完成加载内容时通知您的屏幕。您可以在此处使用Consumer,也可以使用FutureBuilder 获取getListing(),具体取决于您的需要。

使用 FutureBuilder 时,您可能会更改为 Provider 中的内容:

Future<List<Listing>> getListing(Token token) async {
  var response = await http.get(
    url,
    headers: {
      'content-type': 'application/json',
      'accept': 'application/json',
      'authorization': "Bearer ${token.token}"
    },
  );

  final nowListingResponse = ListingResponse.fromJson(response.body);
  return nowListingResponse.results;
}

可以像这样在你的屏幕上消费:

 @override
  Widget build(BuildContext context) {
    
    final listingProvider = Provider.of<ListingProvider>(
      context,
    );

    return Scaffold(
      appBar: AppBar(
        title: const Text("Find Shipments"),
      ),
      body: Center(
        child: Text("Hola ${widget.token.user.name}!"),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            MyHeaderDrawer(
              token: widget.token,
            ),
            FutureBuilder<List<Account>>(
              future: listingProvider.getListing(),
              builder: (context, listSnapshot) {
                 if (listSnapshot.hasError) {
                    // Handle error case);
                 } else if (listSnapshot.connectionState == ConnectionState.done) {
                   return myDrawerListOption(listSnapshot.data);
                 } else {
                      // Handle loading
                 }                     
              }),
          ],
        ),
      ),
    );
  }

类似的东西。该代码可能有一些语法问题,因为我无法对其进行测试。

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 2021-01-06
    • 2019-10-27
    • 1970-01-01
    • 2021-12-15
    • 2021-11-08
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多