Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

dart - Flutter item not updating in widget when delete need to come back to see changes

I have a simple cart page I am showing products on the cart page. The issue is when I am deleting an item it's deleting but in the widget, it's not deleting I need to go back and come again to show the changes. I try to rise setState also but not working.

My code

class _CartPageState extends State<CartPage> {
  num amount = 0;
  bool checkLogin = false;

  void navigateToAddressPage() {
    Get.to(AddressPage());
  }

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

    String imi = await storage.read(key: "imei");
    print(imi);

    if (imi == "loginhuavaha") {
      setState(() {
        this._query();
        checkLogin = true;
      });
    }
  }

  @override
  void initState() {
    setState(() {
      this.check();
    });
  }

  List<Widget> textWidgetList = List<Widget>();

  void _query() async {


    print('cart');
    final dbHelper = DatabaseHelper.instance;

    final allRows = await dbHelper.queryAllRows();

    allRows.forEach((row) {
      amount += double.parse(row['price']);
      print(amount);
      print(row);
    });

    for (int i = 0; i < allRows.length; i++) {
      textWidgetList.add(Card(
        elevation: 5.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.0),
        ),
        margin: EdgeInsets.symmetric(vertical: 8.0),
        child: Container(
          width: double.infinity,
          height: 120.0,
          padding: EdgeInsets.all(12.0),
          child: Row(
            children: [
              ClipRRect(
                  borderRadius: BorderRadius.circular(12.0),
                  child: Image.network(allRows[i]['image'],
                      width: 100, height: 100)),
              SizedBox(width: 12.0),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Text(
                              allRows[i]['title'],
                              textAlign: TextAlign.start,
                              maxLines: 3,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          SizedBox(width: 5.0),
                          Row(
                            children: [
                              GestureDetector(
                                onTap: () async {
                                  print('delete');
                                  final id = await dbHelper.queryRowCount();
                                  print(id);
                                  final rowsDeleted = await dbHelper.delete(
                                      id, allRows[i]['id']);
                                  print('deleted $rowsDeleted row(s): row $id');

                                  setState(() {
                                    
                                  });
                                },
                                child: Icon(
                                  FlutterIcons.delete_outline_mco,
                                ),
                              )
                            ],
                          )
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Text(
                              allRows[i]['price'],
                            ),
                          ),
                          // Counter(),
                        ],
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ));
    }

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: checkLogin
          ? Container(
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 18.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Column(children: textWidgetList),
                  ],
                ),
              ),
            )
          : Center(
              child: Container(
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                    Container(child: Text('Your are not login')),
                    SizedBox(height: 10),
                    SizedBox(
                      width: 85.0,
                      height: 50.0,
                      child: RaisedButton(
                        color: Theme.of(context).primaryColor,
                        elevation: 0.0,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        child: Text(
                          'LOGIN',
                          style: Theme.of(context).textTheme.button,
                        ).tr(),
                        onPressed: () {
                          Get.offAll(SignInPage());
                        },
                      ),
                    ),
                  ])),
            ),
    );
  }

You can see I have added a comment in my code I delete the product and it actually deleted from database but state isn't changing of widget -_-

question from:https://stackoverflow.com/questions/65934011/flutter-item-not-updating-in-widget-when-delete-need-to-come-back-to-see-changes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think what you need here is the Provider package. Provider makes state management easier a lot. Just define a model class that extends ChangeNotifier and then wrap your widgets with ChangeNotifierProvider<Model_class_name>. To access the fields Use Provider.of(context).var or Provider.of(context).function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...