Flutter State对象未在changeNotifierProvider中更新

时间:2020-08-13 08:03:33

标签: flutter provider state-management flutter-state changenotifier

我做了一个changenotifierprovider,然后更改了其中的一些数据,当我打印它时,它显示了更新的数据。

但是,当我尝试获取相同的数据对象时,它显示的是存储在其中的先前版本,而不是最新的更新数据。

我还使用了notifyListeners();在其中进行更新,以便可以在所有正在使用数据的地方进行更新,但是不会发生。

data.dart文件:(提供者)

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import '../Desktop/data_format.dart';
import '../auth/auth-api.dart' as auth;

class DataProvider with ChangeNotifier {
  bool _subscribed = false;

  List<DataTemplate> _data = [];

  List<CategoryTemplate> _categorydata = [];

  List<CategoryTemplate> get categorylist {
    return [..._categorydata];
  }

  List<DataTemplate> get datalist {
    print("New Data: $_data _subscribed = $_subscribed");
    return [..._data];
  }

  bool get subscription {
    return _subscribed;
  }

  Future<void> checkSubscription() async {
    print("Checking Subscription");
    try {
      var _response = await http.get(auth.urlallusers);
      var _extracteddata = jsonDecode(_response.body) as Map<String, dynamic>;
      if (_extracteddata == null) {
        return;
      } else {
        print("You User id is subscribed");
        _subscribed = true;
      }
    } catch (error) {
      print("Not Subscribed");
      throw (error);
    }
    notifyListeners();
  }

  Future<bool> fetchData({bool force = false}) async {
    if (_data.length == 0 || force == true) {
      _data.clear();
      String urldata;
      await checkSubscription();
      _subscribed ? urldata = auth.urldata : urldata = auth.urldemo;
      try {
        _subscribed ? print("Fetching data") : print("Fetching demo");
        var _response = await http.get(urldata);
        var _extracteddata = jsonDecode(_response.body) as Map<String, dynamic>;
        List<DataTemplate> _loadeddata = [];
        int itr = 0;
        List<CategoryTemplate> _categoryloadeddata = [];
        _extracteddata.forEach((category, subcategory) {
          var _newdata = CategoryTemplate(
            id: itr,
            category: category,
            subcategory: [],
          );
          Map<String, dynamic> _subcategorylist = subcategory;
          _subcategorylist.forEach((subcategoryname, names) {
            _newdata.subcategory.add(subcategoryname);
            Map<String, dynamic> name = names;
            name.forEach((nametext, value) {
              _loadeddata.add(
                DataTemplate(
                  id: itr,
                  category: category,
                  subcategory: subcategoryname,
                  name: nametext,
                  address: _subscribed ? value['address'] : "demo",
                  email: _subscribed ? value['mail'] : "demo",
                  phonenumber: _subscribed ? value['mob'] : ["demo"].toList(),
                ),
              );
              itr++;
            });
          });
          _categoryloadeddata.add(_newdata);
        });
        _loadeddata.forEach((element) {
          _data.add(element);
        });
        _categoryloadeddata.forEach((element) {
          _categorydata.add(element);
        });
        notifyListeners();
        print("Data: $_data");
        return false;
      } catch (error) {
        print("Error has occured during fetching data/demo");
        throw (error);
      }
    } else {
      print("All people data has already been fetched");
      return false;
    }
  }

  void addCategory() {
    // _categorylist.add(value);
    notifyListeners();
  }
}

categorypage.dart文件:(正在调用数据的地方)

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../Desktop/data_format.dart';
import '../providers/data.dart';
import '../Desktop/categorytiles.dart';
import 'datatiles.dart';
import '../providers/category.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  bool _pagecategory = true;
  DataProvider _dataProvider;
  List<DataTemplate> _filteredpeople;
  List<CategoryTemplate> _categorylist;
  bool _isLoadingCategory = true;
  bool _isLoadingData = true;
  bool _isInit = true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("_isInit = $_isInit");
    print("Is loading Category: $_isLoadingCategory");
    if (_isInit) {
      fetchData();
    }
    _dataProvider = Provider.of<DataProvider>(context);
    setState(() {
      _filteredpeople = _dataProvider.datalist;
      _categorylist = _dataProvider.categorylist;
    });
    print("_filteredpeople = $_filteredpeople");
    _isInit = false;
  }

  void fetchData() {
    Provider.of<CategoryProvider>(context).fetchCategoryData().then((check) => {
          setState(() {
            _isLoadingCategory = check;
          }),
          print("Is loading Category: $_isLoadingCategory"),
        });
    Provider.of<DataProvider>(context).fetchData().then((check) => {
          setState(() {
            _isLoadingData = check;
          }),
          print("Is loading Data: $_isLoadingData"),
        });
  }

  void _togglePage(bool _switchme) {
    setState(
      () {
        _pagecategory = _switchme;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffd4e6f1),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton(
        elevation: 3,
        backgroundColor: Color(0xff1b4f72),
        child: Icon(
          Icons.arrow_back_ios,
          color: Colors.white,
          size: 20,
        ),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      body: SafeArea(
        child: Container(
          margin: EdgeInsets.only(top: 20),
          child: Column(
            children: <Widget>[
              //SearchTab
              Card(
                shadowColor: Colors.blue[300],
                color: Colors.white,
                margin: EdgeInsets.symmetric(vertical: 5, horizontal: 30),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(40)),
                elevation: 4,
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 25, vertical: 10),
                  padding: EdgeInsets.all(10),
                  child: TextField(
                    cursorColor: Color(0xff5499c7),
                    textAlign: TextAlign.justify,
                    style: TextStyle(
                      color: Color(0xdd1a5276),
                      fontFamily: "roboto",
                    ),
                    decoration: InputDecoration(
                      focusColor: Colors.black,
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Color(0xff5499c7),
                          width: 2,
                        ),
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Color(0xff5499c7),
                          width: 2,
                        ),
                      ),
                      suffixIcon: Container(
                        child: IconButton(
                          icon: Icon(
                            Icons.search,
                            color: Color(0xff5499c7),
                          ),
                          onPressed: () {},
                        ),
                      ),
                      hintText:
                          _pagecategory ? "Search Category" : "Search People",
                      hintStyle: TextStyle(
                        fontFamily: "roboto",
                        color: Color(0x881a5276),
                      ),
                    ),
                    onChanged: (text) {
                      setState(() {
                        _pagecategory
                            ? _categorylist = _dataProvider.categorylist
                                .where((u) => u.category
                                    .toLowerCase()
                                    .contains(text.toLowerCase()))
                                .toList()
                            : _filteredpeople = _dataProvider.datalist
                                .where((u) => (u.name
                                        .toLowerCase()
                                        .contains(text.toLowerCase()) ||
                                    u.address
                                        .toLowerCase()
                                        .contains(text.toLowerCase()) ||
                                    u.subcategory
                                        .toLowerCase()
                                        .contains(text.toLowerCase())))
                                .toList();
                      });
                    },
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    FlatButton(
                      highlightColor: Colors.transparent,
                      splashColor: Colors.transparent,
                      color: _pagecategory
                          ? Color(0xff5499c7)
                          : Colors.transparent,
                      child: Text(
                        "Category",
                        style: TextStyle(
                          fontFamily: "roboto",
                          color:
                              _pagecategory ? Colors.white : Color(0xff5499c7),
                        ),
                      ),
                      onPressed: () {
                        _togglePage(true);
                      },
                    ),
                    FlatButton(
                      highlightColor: Colors.transparent,
                      splashColor: Colors.transparent,
                      color: _pagecategory
                          ? Colors.transparent
                          : Color(0xff5499c7),
                      child: Text(
                        "All People",
                        style: TextStyle(
                          fontFamily: "roboto",
                          color:
                              _pagecategory ? Color(0xff5499c7) : Colors.white,
                        ),
                      ),
                      onPressed: () {
                        _togglePage(false);
                      },
                    ),
                  ],
                ),
              ),
              // data region
              Expanded(
                child: GestureDetector(
                  onHorizontalDragUpdate: (details) {
                    details.delta.dx > 0
                        ?
                        //Right Swipe
                        _togglePage(true)
                        : //Left Swipe
                        _togglePage(false);
                  },
                  child: _pagecategory
                      ? _isLoadingCategory
                          ? Center(
                              child: CircularProgressIndicator(),
                            )
                          : ListView.builder(
                              padding: EdgeInsets.all(10),
                              itemCount: _categorylist.length,
                              itemBuilder: (ctx, index) {
                                var dataitr = _categorylist[index];
                                return Container(
                                  key: ValueKey(dataitr.id),
                                  child: CategoryTile(
                                      category: dataitr.category,
                                      subcategory: dataitr.subcategory),
                                );
                              },
                            )
                      : _isLoadingData
                          ? Center(
                              child: CircularProgressIndicator(),
                            )
                          : ListView.builder(
                              padding: EdgeInsets.all(10),
                              itemCount: _filteredpeople.length,
                              itemBuilder: (ctx, index) {
                                var dataitr = _filteredpeople[index];
                                return Container(
                                  key: ValueKey(_filteredpeople[index].id),
                                  child: DataTile(
                                      name: dataitr.name,
                                      category: dataitr.category,
                                      subcategory: dataitr.subcategory,
                                      address: dataitr.address,
                                      email: dataitr.email,
                                      phonenumber: dataitr.phonenumber),
                                );
                              },
                            ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

payment.dart:文件(付款成功后数据会更新)

import 'dart:convert';

import 'package:ShowWorld/models/listed_data.dart';
import 'package:ShowWorld/providers/data.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:razorpay_flutter/razorpay_flutter.dart';

import '../auth/auth-api.dart' as auth;

class PaymentProvider with ChangeNotifier {
  bool _notsubscribed = true;
  Razorpay _razorpaySubscription = Razorpay();

  @override
  void dispose() {
    super.dispose();
    _razorpaySubscription.clear();
    _razorpayListYourself.clear();
  }

  bool get subscriptionstatus {
    return _notsubscribed;
  }

  void httpsubscribed() async {
    var _extract = await http.get(auth.urlallusers);
    _notsubscribed = jsonDecode(_extract.body) == null;
    notifyListeners();
  }

  void _handlePaymentSuccess(PaymentSuccessResponse response) {
    print("Payment Successful");
    _notsubscribed = false;
    notifyListeners();
    Map<String, String> data = {
      'mob': '${auth.user.phoneNumber}',
      'timestamp': '${DateTime.now().toIso8601String()}',
    };
    try {
      sendhttpRequest(data);
      Fluttertoast.showToast(
        msg: "Payment Successful",
        backgroundColor: Colors.green,
      );
    } catch (e) {
      throw (e);
    }
  }

  void sendhttpRequest(Map<String, String> data) async {
    try {
      await http
          .patch(
        auth.urlallusers,
        headers: {"Accept": "application/json"},
        body: jsonEncode(data),
      )
          .then(
        (value) async {
          print("User Added to Subscription List");
          await DataProvider().fetchData(force: true);
          notifyListeners();
        },
      );
    } catch (e) {
      throw (e);
    }
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    print("Payment failed");
    Fluttertoast.showToast(
      msg: "Payment Failed",
      backgroundColor: Colors.red,
    );
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    print("Choosing Wallet");
  }

  void makePayment(double price) {
    _razorpaySubscription.on(
        Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpaySubscription.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpaySubscription.on(
        Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
    var options = {
      'key': '${auth.razorpaykey}',
      'amount': price * 100,
      'name': 'Show World Subscription',
      'description': 'Subscription',
      'prefill': {
        'contact': '${auth.user.phoneNumber}',
      }
    };
    try {
      _razorpaySubscription.open(options);
      notifyListeners();
    } catch (e) {
      throw (e);
    }
  }

调试控制台:

User Added to Subscription List
I/flutter (15578): Checking Subscription
W/libEGL  (15578): EGLNativeWindowType 0x9faf8b08 disconnect failed
D/ViewRootImpl@daf6f43[Toast](15578): dispatchDetachedFromWindow
D/InputTransport(15578): Input channel destroyed: '41874fb', fd=215
I/flutter (15578): You User id is subscribed
I/flutter (15578): Fetching data
D/ViewRootImpl@6e7f972[MainActivity](15578): ViewPostIme key 0
D/ViewRootImpl@6e7f972[MainActivity](15578): ViewPostIme key 1
I/flutter (15578): Data: [Instance of 'DataTemplate', Instance of 'DataTemplate'
, Instance of 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataTempl
ate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataT
emplate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instance of 'D
ataTemplate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instance o
f 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instan
ce of 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataTemplate', In
stance of 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataTemplate'
, Instance of 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataTempl
ate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataT
emplate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instance of 'D
ataTemplate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instance o
f 'DataTemplate', Instance of 'DataTemplate', Instance of 'DataTemplate', Instan
ce
D/ViewRootImpl@6e7f972[MainActivity](15578): ViewPostIme pointer 0
D/ViewRootImpl@6e7f972[MainActivity](15578): ViewPostIme pointer 1
I/flutter (15578): _isInit = true
I/flutter (15578): Is loading Category: true
I/flutter (15578): Category data has already been fetched
I/flutter (15578): All people data has already been fetched
I/flutter (15578): New Data: [Instance of 'DataTemplate', Instance of 'DataTempl
ate', Instance of 'DataTemplate', Instance of 'DataTemplate'] _subscribed = fals
e
I/flutter (15578): _filteredpeople = [Instance of 'DataTemplate', Instance of 'D
ataTemplate', Instance of 'DataTemplate', Instance of 'DataTemplate']
I/flutter (15578): Is loading Category: false
I/flutter (15578): Is loading Data: false

正如您在调试控制台中所看到的,“新数据:”的项目数少于数据:(因为未更新)

0 个答案:

没有答案